我只想绘制一个条形图,如Orange dataset中的下图所示
任何帮助都将不胜感激。
发布于 2018-03-11 22:05:02
我的代码的思想是首先使用case_when
创建ageGroup
列,汇总数据以仅显示每个Tree
和ageGroup
组合的最大值,然后将ageGroup
列转换为因子并对列执行arrange
操作,这与条形图的轴上的顺序相关。
然后,我们可以使用ggplot2
绘制数据。请注意,与不需要调用stat = "identity"
的geom_bar
相比,geom_col
是创建条形图的更简单版本。scale_fill_brewer
可以直接调用colorbrewer调色板,这非常方便。
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")
发布于 2018-03-11 22:05:25
如你所愿,同样的颜色,labes,轴
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()
发布于 2018-03-11 22:33:34
对于变化,一个dplyr
较少的答案。
使用cut
离散化age
变量
Orange$ageGrp <- with(Orange, cut(age, c(0, 250, 900, Inf),
c("Young", "Adult", "old")))
使用position_dodge()
使条形相邻,并设置fun.y=max
以选择最大circumference
。
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
ggplot(Orange, aes(x=ageGrp, y=circumference, fill=Tree)) +
geom_bar(stat="summary", fun.y=max, position=position_dodge()) +
coord_flip()
https://stackoverflow.com/questions/49225313
复制相似问题