2016-09-24 148 views
26

嗨,大家好,我在繪製條形圖時出現此錯誤,但我無法擺脫它,我嘗試了qplot和ggplot但仍然是同樣的錯誤。R ggplot2:stat_count()不得與條形圖中的ay美學錯誤一起使用

以下是我的代碼

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 

數據在data_country

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

,誤差值在條形圖,而不是在虛線圖來。任何建議將非常有幫助

回答

52

首先,你的代碼是有點關閉。 aes()ggplot()一個說法,你不使用ggplot(...) + aes(...) + layers

其次,從幫助文件?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.

你想要的第二種情況,其中條的高度等於在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") 

結果:

enter image description here

+1

是的,工作感謝解釋它,我很小新感謝您的幫助 – Uasthana