Uas*_*ana 73 r bar-chart ggplot2
嗨伙计们,我在绘制条形图时遇到此错误,我无法摆脱它,我已经尝试了qplot和ggplot,但仍然是同样的错误.
以下是我的代码
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()
Run Code Online (Sandbox Code Playgroud)
错误:
stat_count() must not be used with a y aesthetic
Run Code Online (Sandbox Code Playgroud)
data_country中的数据
country conversion_rate
<fctr> <dbl>
1 China 0.001331558
2 Germany 0.062428188
3 UK 0.052612025
4 US 0.037800687
Run Code Online (Sandbox Code Playgroud)
错误来自条形图而不是虚线图表.任何建议都会有很大帮助
Chr*_*sss 126
首先,你的代码有点偏.aes()
是一个参数ggplot()
,你不使用ggplot(...)
+aes(...) + layers
其次,从帮助文件?geom_bar
:
默认情况下,geom_bar使用stat ="count",这使得栏的高度与每组中的案例数成比例(或者如果提供了权重,则为权重的总和).如果您希望条形的高度表示数据中的值,请使用stat ="identity"并将变量映射到y美学.
你想要第二种情况,其中条的高度等于conversion_rate
你想要的是......
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")
Run Code Online (Sandbox Code Playgroud)
结果:
您可以直接使用 geom_col()。在此链接中查看 geom_bar() 和 geom_col() 之间的区别https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() 使条的高度与每组中的案例数成比例 如果您希望条的高度代表数据中的值,请改用 geom_col()。
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
Run Code Online (Sandbox Code Playgroud)
小智 5
当您要使用数据框中现有的数据作为y值时,必须在映射参数中添加stat =“ identity”。函数geom_bar具有默认的y值。例如,
ggplot(data_country)+
geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")
Run Code Online (Sandbox Code Playgroud)