R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

Hi guys I am getting this error while plotting a bar graph and I am not able to get rid of it, I have tried both qplot and ggplot but still the same error.

Following is my code

 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() 

Error:

  stat_count() must not be used with a y aesthetic 

Data in data_country

    country conversion_rate     <fctr>           <dbl>   1   China     0.001331558   2 Germany     0.062428188   3      UK     0.052612025   4      US     0.037800687 

The error is coming in bar chart and not in the dotted chart. Any suggestions would be of great help

回答1:

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

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") 

Result:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!