![](/img/trans.png)
[英]stacked barplot of proportions in R ggplot2 grouped by levels of two factors
[英]Grouped barplot in ggplot2 in R
我想制作一个分组的条形图。 我的数据示例如下:
site code year month gear total value
678490 2012 3 GL 13882
678490 2012 4 GL 50942
678490 2012 5 GL 54973
678490 2012 6 GL 63938
678490 2012 7 GL 23825
678490 2012 8 GL 8195
678490 2012 9 GL 14859
678490 2012 9 RT 3225
678490 2012 10 GL 981
678490 2012 10 RT 19074
678490 2012 11 SD 106384
678490 2012 11 RT 2828
678490 2012 12 GL 107167
678490 2012 12 RT 4514
有17个站点代码选项,四年选项,十二个月选项和四个齿轮选项。
我要生产的是每个站点每年的情节,每个月显示每个装备的“总价值”,作为一个条形码。
到目前为止,我已设法生成一个特定于网站和年份的图,但总价值显示在每个月的一个条形图中,而不是每月分成单独的条形图(不能在第一篇文章中包含图像!)
但是对于9,10,11和12个月,有两个齿轮使用,所以我希望这几个月有两个齿条。
我使用以下代码:
ggplot(subset(cdata, year %in% c("2012") & site code %in% c("678490")),
aes(x = factor(month), y = total value)) +
geom_bar(stat = "identity") +
labs(x = "Month", y = "Total value")
任何有关这方面的帮助将不胜感激。
如果你想为每个gear
分别设置条形,那么你应该在geom_bar
为aes
添加fill=gear
:
ggplot(cdata[cdata$year==2012 & cdata$sitecode==678490,],
aes(x = factor(month), y = totalvalue, fill=gear)) +
geom_bar(stat = "identity", position="dodge") +
labs(x = "Month", y = "Total value")
这给了:
当你想为每个站点制作一个地块,每年显示每个齿轮的“总价值”,对于每个月,作为一个条形,你可以使用facet_grid
。 例如:
ggplot(cdata, aes(x = factor(month), y = totalvalue, fill=gear)) +
geom_bar(stat = "identity", position="dodge") +
labs(x = "Month", y = "Total value") +
facet_grid(sitecode ~ year)
这给了:
一些额外的评论:
因此我编写了一些数据:
df1 <- read.table(text="sitecode year month gear totalvalue
678490 2012 3 GL 13882
678490 2012 4 GL 50942
678490 2012 5 GL 54973
678490 2012 6 GL 63938
678490 2012 7 GL 23825
678490 2012 8 GL 8195
678490 2012 9 GL 14859
678490 2012 9 RT 3225
678490 2012 10 GL 981
678490 2012 10 RT 19074
678490 2012 11 SD 106384
678490 2012 11 RT 2828
678490 2012 12 GL 107167
678490 2012 12 RT 4514", header= TRUE)
df2 <- df1
df2$sitecode <- 7849
df2$year <- 2013
df3 <- df1
df3$sitecode <- 7849
df4 <- df1
df4$year <- 2013
cdata <- rbind(df1,df2,df3,df4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.