在ggplot中显示条形图的图例 [英] Show legend for bar plot in ggplot

查看:124
本文介绍了在ggplot中显示条形图的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I show legend for the following ggplot bar plot?

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 排列的.两种图表的条形数量相同,但其中的一条带有图例.我以为通过在第二个图表中添加任何图例,我将对齐条形(使两个图表的绘图区域的宽度相同):

Update: I have two charts arranged using grid.arrange from gridExtra. 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:

推荐答案

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

You can try something like this for p2, which will create a new legend for the bottom graph.

p2 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1, fill = 0), stat = 'identity') +
    guides(fill=guide_legend(title="Title"))

这篇关于在ggplot中显示条形图的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆