简体   繁体   English

在ggplot中显示条形图的图例

[英]Show legend for bar plot in ggplot

How do I show legend for the following ggplot bar plot? 如何显示以下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')

Update: I have two charts arranged using grid.arrange from gridExtra . 更新:我有两个图表使用grid.arrangegridExtra Both charts have the same number of bars, but one has legend. 两种图表的条形数量相同,但其中的一条带有图例。 I thought that by adding any legend to the second chart, I will align the bars (make width of plot area of both plots the same): 我以为,通过在第二张图表中添加任何图例,我将对齐条形(使两个图表的绘图区域的宽度相同):

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

Now, it looks like this: 现在,它看起来像这样:

在此处输入图片说明

You can try something like this for p2, which will create a new legend for the bottom graph. 您可以为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"))

This is what i needed 这就是我所需要的

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

Thanks 谢谢

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

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