简体   繁体   English

X轴堆叠条形图上的多列

[英]Multiple columns on x-axis stacked bar charts

I'm beginner in R programming, exploring ggplot. 我是R编程的初学者,正在研究ggplot。 I'm trying to plot stacked bar chart to show 3 years quarterly revenue for multiple countries. 我正在尝试绘制堆积条形图,以显示多个国家/地区3年的季度收入。 I'm using data from https://www.ibm.com/communities/analytics/watson-analytics-blog/sales-products-sample-data/ 我正在使用https://www.ibm.com/communities/analytics/watson-analytics-blog/sales-products-sample-data/中的数据

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

above ggplot is giving me 上面的ggplot给了我 在此处输入图片说明 what I want is to have 3 bars for each year grouped together for each country. 我想要的是每个国家每年有3个酒吧。 Can anyone advise how to achieve it? 谁能建议如何实现它?

Here I put Quarter instead of Year on x-axis, otherwise you would need to use facets. 在这里,我在X轴上放置了Quarter而不是Year ,否则您将需要使用构面。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM