在 ggplot 中显示条形图的图例

Show legend for bar plot in ggplot

如何显示以下 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')

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

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

现在,它看起来像这样:

您可以为 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"))

这就是我需要的

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

谢谢