[英]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.