加入传奇“geom_bar”使用包GGPLOT2(Add legend to “geom_bar”

2019-07-03 19:19发布

我是一个新手到R,所以请原谅我的无知。 余由伪堆叠barplot其中我画上彼此使用geom_bar的顶部4套杆。 有4个健康状况类别(活的,死的,感染,与SOD-死亡)三个品种橡树(泥沼,QUKE,QUCH)。

我的代码如下:


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”是“死树”等,我一直在尝试了几个小时了,不能让它的工作。

Answer 1:

我看到@Brandon贝特尔森发布了一个伟大的答案。 我想补充一些代码,解决了原来的帖子中提到的其他详细信息:

  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)

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



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


文章来源: Add legend to “geom_bar” using the ggplot2 package
标签: r ggplot2