1

如何显示以下 ggplot 条形图的图例?

tmp <- data.frame(group = LETTERS[1:10], id = 10:1, a = runif(10), b = runif(10))

ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1), stat = 'identity')

更新:我有两个使用grid.arrangefrom排列的图表gridExtra。两张图表的条数相同,但一张有图例。我认为通过在第二个图表中添加任何图例,我将对齐条形(使两个图的绘图区域的宽度相同):

tmp <- data.frame(group = LETTERS[1:10], id = 10:1, 
                  a = runif(10), b = runif(10), c = rnorm(10))

p1 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), c, fill = a), stat = 'identity')
p2 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1), stat = 'identity')

library(gridExtra)

grid.arrange(p1, p2, heights = c(2, 1) )

现在,它看起来像这样:

在此处输入图像描述

4

2 回答 2

2

您可以为 p2 尝试类似的操作,这将为底部图形创建一个新的图例。

p2 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1, fill = 0), stat = 'identity') +
    guides(fill=guide_legend(title="Title"))
于 2015-01-22T22:35:40.997 回答
0

这就是我需要的

 guides(fill=guide_legend(title="Title"))

谢谢

于 2017-05-06T23:06:06.763 回答