繁体   English   中英

使用ggplot2包将图例添加到“geom_bar”

[英]Add legend to “geom_bar” using the ggplot2 package

我是R的新手,所以请原谅我的无知。 我制作了一个伪堆叠的条形图,其中我使用geom_bar在彼此的顶部绘制了4组条形图。 三种橡树(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

现在我想制作一个传说,显示哪个灰色阴影与树状态有关,即“灰色65”是“死树”等等。我一直在尝试过去一小时而无法让它工作。

我看到@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)

在此输入图像描述

您需要重塑数据。

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

暂无
暂无

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

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