2012-11-12 99 views
10

我是R的新手,所以請原諒我的無知。我做了一個僞堆疊的barplot,其中我使用geom_bar在彼此的頂部繪製了4組條。三種橡樹(QUAG,QUKE,QUCH)有4種健康狀況類別(活着,死亡,感染,& sod-dead)。使用ggplot2包將圖例添加到「geom_bar」

我的代碼如下:


x <- as.data.frame(list(variable=c("QUAG", "QUKE", "QUCH"), alive = c(627,208,109), infected = c(102,27,0), dead = c(133,112,12), sod.dead=c(49,8,0))) 

x.plot = ggplot(x, aes(variable, alive)) + geom_bar(fill="gray85") + 
    geom_bar(aes(variable,dead), fill="gray65") + 
    geom_bar(aes(variable, infected), fill="gray38") + 
    geom_bar(aes(variable, sod.dead), fill="black")+ 
    opts(panel.background = theme_rect(fill='gray100')) 
x.plot 

現在我想打一個傳奇,顯示其灰色遮陽涉及到樹狀態,即「gray65」是「死樹「等等,我一直在嘗試過去的一小時,並且無法實現它的工作。

+3

1爲簡潔再現的例子。 – mnel

回答

2

您需要重新整理數據。

library(reshape) 
library(ggplot2) 

x <- as.data.frame(list(variable=c("QUAG", "QUKE", "QUCH"), alive = c(627,208,109), infected = c(102,27,0), dead = c(133,112,12), sod.dead=c(49,8,0))) 

x <- melt(x) 
colnames(x) <- c("Type","Status","value") 

ggplot(x, aes(Type, value, fill=Status)) + geom_bar(position="stack") 
+0

謝謝布蘭登! –

8

我看到@Brandon Bertelsen已經發布了一個很好的答案。我想補充一些代碼,解決了原來的帖子中提到的其他詳細信息:

  1. 你重塑你的數據和健康狀況映射到fill後,ggplot會自動創建的傳說。
  2. 我建議使用scale_fill_manual()來獲得原始帖子中提到的確切灰色。
  3. theme_bw()是一種方便快捷的功能,可以快速將黑白相片呈現給您的情節。
  4. 可以通過指定levels參數factor()的參數指定所需的順序來控制因子級別/顏色的繪製順序。
  5. 躲閃的barplot(而不是堆疊)可能對此數據集有一些優點。

library(reshape2) 
library(ggplot2) 

x <- as.data.frame(list(variable=c("QUAG", "QUKE", "QUCH"), 
         alive=c(627, 208, 109), infected=c(102, 27, 0), 
         dead=c(133, 112, 12), sod.dead=c(49, 8, 0))) 

# Put data into 'long form' with melt from the reshape2 package. 
dat = melt(x, id.var="variable", variable.name="status") 

head(dat) 
# variable status value 
# 1  QUAG alive 627 
# 2  QUKE alive 208 
# 3  QUCH alive 109 
# 4  QUAG infected 102 
# 5  QUKE infected 27 
# 6  QUCH infected  0 

# By manually specifying the levels in the factor, you can control 
# the stacking order of the associated fill colors. 
dat$status = factor(as.character(dat$status), 
        levels=c("sod.dead", "dead", "infected", "alive")) 

# Create a named character vector that relates factor levels to colors. 
grays = c(alive="gray85", dead="gray65", infected="gray38", sod.dead="black") 

plot_1 = ggplot(dat, aes(x=variable, y=value, fill=status)) + 
     theme_bw() + 
     geom_bar(position="stack") + 
     scale_fill_manual(values=grays) 

ggsave(plot=plot_1, filename="plot_1.png", height=5, width=5) 

enter image description here

# You may also want to try a dodged barplot. 
plot_2 = ggplot(dat, aes(x=variable, y=value, fill=status)) + 
     theme_bw() + 
     geom_bar(position="dodge") + 
     scale_fill_manual(values=grays) 

ggsave(plot=plot_2, filename="plot_2.png", height=4, width=5) 

enter image description here

+2

+1。 –

+0

兩種方法都奏效。非常感謝!我只是訂購了「ggplot2」書,所以希望我能和你們一樣好。 –