我向Orange数据集添加了一个列,如下所示:
Orange$ageGroup = cut(Orange$age, breaks = c(0,250,900,Inf), labels = c("Young", "Adult", "Old"))
然后我应用了一个聚合函数来创建mean_Orange
:
> mean_Orange <- aggregate(. ~ Tree+ageGroup, Orange[,c("Tree","circumference","ageGroup")], mean)
> mean_Orange
Tree ageGroup circumference
1 3 Young 30.00
2 1 Young 30.00
3 5 Young 30.00
4 2 Young 33.00
5 4 Young 32.00
6 3 Adult 63.00
7 1 Adult 72.50
8 5 Adult 65.00
9 2 Adult 90.00
10 4 Adult 87.00
11 3 Old 125.50
12 1 Old 130.50
13 5 Old 154.50
14 2 Old 183.50
15 4 Old 192.25
现在,我被要求创建一个如下所示的barplot:
我尝试了以下命令,并遇到错误:
> ggplot(mean_Orange, aes(x=ageGroup, y=circumference, fill=as.factor(Tree))) +
+ geom_bar() +
+ coord_flip() # this is used in order to invert the axis orientation
Error: stat_count() must not be used with a y aesthetic.
能否请您指导我如何使用ggplot库进行上述绘制?
答案 0 :(得分:1)
y
与geom_col
一起使用:
ggplot(mean_Orange, aes(x=ageGroup, y=circumference, fill=as.factor(Tree))) +
geom_col(position = "dodge") +
coord_flip() # this is used in order to invert the axis orientation
您可以将geom_col
与position="dodge"
一起使用。