R ggplot2:stat_count()不能与条形图中的y美学错误一起使用
我在绘制条形图时遇到了这个错误,我无法消除它,我尝试了qplot和ggplot,但仍然是相同的错误 以下是我的代码:R ggplot2:stat_count()不能与条形图中的y美学错误一起使用,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,我在绘制条形图时遇到了这个错误,我无法消除它,我尝试了qplot和ggplot,但仍然是相同的错误 以下是我的代码: library(dplyr) library(ggplot2) #Investigate data further to build a machine learning model data_country = data %>% group_by(country) %>% summarise(conversion
library(dplyr)
library(ggplot2)
#Investigate data further to build a machine learning model
data_country = data %>%
group_by(country) %>%
summarise(conversion_rate = mean(converted))
#Ist method
qplot(country, conversion_rate, data = data_country,geom = "bar", stat ="identity", fill = country)
#2nd method
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_bar()
错误:
stat_count() must not be used with a y aesthetic
数据所在国家/地区的数据:
country conversion_rate
<fctr> <dbl>
1 China 0.001331558
2 Germany 0.062428188
3 UK 0.052612025
4 US 0.037800687
国家/地区转换率
1中国0.001331558
2德国0.062428188
3英国0.052612025
4美元0.037800687
错误出现在条形图中,而不是虚线图中。首先,您的代码有点错误
aes()
是ggplot()
中的参数,您不使用ggplot(…)
+aes(…)+层
其次,从帮助文件?geom_bar
:
默认情况下,geom_bar使用stat=“count”,这会使
与每组病例数的比例(或如果重量
提供了aethetic,即重量之和)。如果你想要高度
在表示数据中值的条形图中,使用stat=“identity”和
将变量映射到y轴
您需要第二种情况,其中条形图的高度等于转换率,因此您需要的是
data_country <- data.frame(country = c("China", "Germany", "UK", "US"),
conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")
data\u country我一直在寻找相同的数据,这也可能有效
p.Wages.all.A_MEAN <- Wages.all %>%
group_by(`Career Cluster`, Year)%>%
summarize(ANNUAL.MEAN.WAGE = mean(A_MEAN))
p.sweels.all.A_平均值%
分组依据(‘职业集群’,年份)%>%
汇总(年平均工资=平均值)
姓名(p.工资、全部A_平均值)
[1] “职业群”“年”“年平均工资”
p.sweels.all.a.mean当您想使用数据框中现有的数据作为y值时,必须在映射参数中添加stat=“identity”。函数geom_bar具有默认的y值。比如说,
ggplot(data_country)+
geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")
您可以直接使用geom_col()。请参见此链接中geom_bar()和geom_col()之间的差异
geom_bar()使条形图的高度与每组中的案例数成比例如果希望条形图的高度表示数据中的值,请改用geom_col()
是的,谢谢你的解释,我对此并不陌生,感谢你的帮助澄清,aes
实际上是一个函数。ggplot
的参数是mapping
。我们通过aes
函数提供映射,因此您可以看到很多模式ggplot(df,aes(…)
。但是模式ggplot(数据帧)+aes(x=x,y=y)也很好。除了可能提高可读性外,单独调用aes
还可以用来修改预制图的美观性:p截至2020年(以及很久以前),ggplot(…)+aes(…)+layers
。可以确认我一直存在此问题,这是最简单的解决方案。
ggplot(data_country)+
geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()