首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >内置数据集绘图

内置数据集绘图
EN

Stack Overflow用户
提问于 2018-03-12 05:31:05
回答 4查看 345关注 0票数 0

我只想绘制一个条形图,如Orange dataset中的下图所示

任何帮助都将不胜感激。

EN

回答 4

Stack Overflow用户

发布于 2018-03-12 06:05:02

我的代码的思想是首先使用case_when创建ageGroup列,汇总数据以仅显示每个TreeageGroup组合的最大值,然后将ageGroup列转换为因子并对列执行arrange操作,这与条形图的轴上的顺序相关。

然后,我们可以使用ggplot2绘制数据。请注意,与不需要调用stat = "identity"geom_bar相比,geom_col是创建条形图的更简单版本。scale_fill_brewer可以直接调用colorbrewer调色板,这非常方便。

代码语言:javascript
代码运行次数:0
运行
复制
data("Orange")

library(dplyr)
library(ggplot2)

Orange2 <- Orange %>%
  mutate(ageGroup = case_when(
    age <= 250                 ~"Young",
    age > 250 & age <= 900     ~"Adult",
    age > 900                  ~"Old"
  )) %>%
  group_by(Tree, ageGroup) %>%
  summarise(circumference = max(circumference)) %>%
  ungroup() %>%
  mutate(ageGroup = factor(ageGroup, levels = c("Young", "Adult", "Old"))) %>%
  arrange()


ggplot(Orange2, aes(x = ageGroup, y = circumference, fill = Tree)) +
  geom_col(position = position_dodge()) +
  scale_x_discrete(name = "Age Group") +
  scale_y_continuous(name = "Circumference") +
  coord_flip() +
  scale_fill_brewer(type = "qual", palette = "Paired") +
  theme_bw() +
  ggtitle("Growth of Orange Trees")

票数 3
EN

Stack Overflow用户

发布于 2018-03-12 06:05:25

如你所愿,同样的颜色,labes,轴

代码语言:javascript
代码运行次数:0
运行
复制
library(tidyverse)
color_palette <- c("#a5cde2", "#1e78b5",  "#b0dd89", "#33a02b", "#f99a98")
Orange %>% 
  mutate(AgeGroup=ifelse(age<250, "young", ifelse(age>900, "old", "adult"))) %>% 
  group_by(Tree, AgeGroup) %>%
  summarise(circumference = max(circumference)) %>%
  ggplot(aes(AgeGroup, circumference, fill=Tree)) +
  geom_bar(position = "dodge", stat="identity") +
  scale_x_discrete(limits=c("young","adult", "old")) +
  coord_flip() +
  scale_fill_manual(values = color_palette) +
  theme_bw()

票数 1
EN

Stack Overflow用户

发布于 2018-03-12 06:33:34

对于变化,一个dplyr较少的答案。

使用cut离散化age变量

代码语言:javascript
代码运行次数:0
运行
复制
Orange$ageGrp <- with(Orange, cut(age, c(0, 250, 900, Inf), 
                                  c("Young", "Adult", "old")))

使用position_dodge()使条形相邻,并设置fun.y=max以选择最大circumference

代码语言:javascript
代码运行次数:0
运行
复制
library(ggplot2)    
ggplot(Orange, aes(x=ageGrp, y=circumference, fill=Tree)) +
               stat_summary(geom="bar", fun.y=max, position=position_dodge()) +
               coord_flip()

或者直接使用geom_bar

代码语言:javascript
代码运行次数:0
运行
复制
ggplot(Orange, aes(x=ageGrp, y=circumference, fill=Tree)) +
               geom_bar(stat="summary", fun.y=max, position=position_dodge()) + 
               coord_flip()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49225313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档