2017-10-06 108 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