2017-10-06 99 views
0

我是R編程的初學者,探索ggplot。我試圖繪製堆積的條形圖,以顯示多個國家的3年季度收入。 我使用的數據來自https://www.ibm.com/communities/analytics/watson-analytics-blog/sales-products-sample-data/x軸堆疊條形圖上的多列

mydata <- read.csv("~/Downloads/WA_Sales_Products_2012-14.csv") 
library(dplyr) 
qtrSales <- mydata %>% 
group_by(mydata$Retailer.country, mydata$Year, mydata$Quarter) %>% 
summarize(Rev=sum(Revenue)) %>% 

qtrSales <- data.frame(qtrSales) 
colnames(qtrSales) <- c("Country", "Year", "Qtr", "Revenue") 

library(ggplot2) 
ggplot() + geom_bar(aes(y=qtrSales$Revenue, x = qtrSales$Year, 
fill=qtrSales$Qtr), data=qtrSales, stat="identity") 

上述ggplot是給我enter image description here 我要的是有每年每個國家聚集在一起爲3條。任何人都可以建議如何實現它?

+0

你的宿舍太需要組?有21個國家和堆疊的geom_bar看起來很糟糕,我建議使用別的 – PoGibas

+1

,你可以在facet_wrap中添加一年,這樣你就可以看到季度增長。如果你已經分組了吧,它不會很好讀,但是如果你堅持,看看position =「dodge」 – User632716

+0

謝謝你的回覆。請原諒我缺乏知識,你還有什麼建議?我想你說的對所有21個國家都顯得混亂。如果我改變方案,限制5個或10個國家,是否可以根據我原來的要求完成? –

回答

1

在這裏我把Quarter而不是Year在X軸上,否則你需要使用facets。

colnames(mydata)[1] <- "Country" 
library(ggplot2) 
ggplot(mydata, aes(Quarter, Revenue, fill = Country)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    scale_x_discrete(limits = unique(mydata$Quarter)) + 
    theme(legend.position = "bottom") + 
    guides(fill = guide_legend(nrow = 2)) 

enter image description here

+0

@ssjsk還有什麼其他的你想要顯示/調整嗎? – PoGibas

+1

真棒,感謝你的這一個,我會探索更多使用方面,以瞭解更多:-)感謝您的快速反應。 –

+0

@ssjsk高興地幫助:-) – PoGibas