使用ggplot2包在“geom_bar”中添加图例

13

我对R是个新手,请谅解我的无知。我使用geom_bar制作了一个伪堆积条形图,在其中将4组柱状图叠在一起。有3种橡树(QUAG,QUKE,QUCH)的4种健康状态分类(活着,死了,感染了和枯萎死亡)。

我的代码如下:


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个回答

10

我看到@Brandon Bertelsen发布了一个很棒的答案。我想加入一些代码,以解决原始帖子中提到的其他细节:

  1. 在你重塑数据并将健康状态映射到fill之后,ggplot会自动创建图例。
  2. 我建议使用scale_fill_manual()来获得原帖中提到的确切灰度。
  3. theme_bw()是一个方便的函数,可以快速使你的图表呈现黑白效果。
  4. 因子级别/颜色的绘图顺序可以通过在factor()levels参数中指定所需顺序来控制。
  5. 这个数据集可能使用分组条形图(而不是堆叠)会更有优势。

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)

在这里输入图像描述

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

输入图像描述


两种方法都行。非常感谢!我刚刚订购了《ggplot2》这本书,希望我能和你们两个一样厉害。 - Sarah Haas

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接