我使用ggplot2按月创建直方图。我能够很容易地得到我想要的情节结构,但似乎无法让传说变得非常正确。
理想情况下,我可以抑制与直方图填充相关联的图例,因为该信息通过构面标题显而易见。我希望有一个关于我画的垂直线的图例,一个在零,一个在每个组的平均值。
这里的一些代码让我非常接近,但我似乎无法得到传奇。在过去,我在scale_color_manual()
取得了成功,但它似乎让我失望(即我似乎在这里让它失望)。
library(ggplot2)
set.seed(232)
## Data that are somewhat similar to mine
df = data.frame(var=c(rnorm(250, 0.5, 1),
rnorm(250, 1.1, 1),
rnorm(250),
rnorm(250, -0.8, 1)),
month=factor(c(rep('Jan', 250),
rep('Feb', 250),
rep('Mar', 250),
rep('Apr', 250)),
levels=c('Jan', 'Feb',
'Mar', 'Apr')))
## I couldn't get ggplot2 to calculate the means within an aes() call,
## so I'm calculating them myself using aggregate
means = aggregate(var ~ month, df, mean)
## Vector of colors with names I want in legend
cols = c('Zero'='black', 'Mean'='#990000')
## Current plot code that doesn't quite give me what I want.
## This is missing the legend from scale_color_manual() for the vlines
hists = ggplot(data=df) +
geom_histogram(aes(var, fill=month)) +
facet_wrap( ~ month) +
geom_vline(aes(xintercept=0, color='Zero')) +
geom_vline(aes(xintercept=var, color='Mean'), data=means) +
scale_color_manual(name='', values=cols) +
guides(fill=FALSE)
print(hists)
这里没有传说,它目前的样子。我想要这样,但有垂直线的图例: 有什么建议?谢谢!
答案 0 :(得分:1)
尝试将means
修改为:
> means
month var col
1 Jan 0.53487078 red
2 Feb 1.16130990 red
3 Mar 0.06391861 red
4 Apr -0.76902156 red
5 Jan 0.00000000 black
6 Feb 0.00000000 black
7 Mar 0.00000000 black
8 Apr 0.00000000 black
...然后试试这个:
hists = ggplot(data=df) +
geom_histogram(aes(var, fill=month)) +
facet_wrap( ~ month) +
geom_vline(aes(xintercept=var, color=col), data=means,show_guide = TRUE) +
scale_color_manual(name='', values=c('black','red')) +
guides(fill=FALSE)
print(hists)
...然后调整数据框列col
以使图例说出您想要的内容。
从OP编辑 - 最终代码:
library(ggplot2)
set.seed(232)
df = data.frame(var=c(rnorm(250, 0.5, 1),
rnorm(250, 1.1, 1),
rnorm(250),
rnorm(250, -0.8, 1)),
month=factor(c(rep('Jan', 250),
rep('Feb', 250),
rep('Mar', 250),
rep('Apr', 250)),
levels=c('Jan', 'Feb',
'Mar', 'Apr')))
means = aggregate(var ~ month, df, mean)
means$col = rep('Mean', nrow(means))
means = rbind(means, data.frame(month=means$month,
var=rep(0, nrow(means)),
col=rep('Zero', nrow(means))))
cols = c('Mean'='#990000', 'Zero'='black')
hists = ggplot(data=df) +
geom_histogram(aes(var, fill=month)) +
facet_wrap( ~ month) +
geom_vline(aes(xintercept=var, color=col), data=means, show_guide=TRUE) +
scale_color_manual(name='', values=cols) +
guides(fill=FALSE)
print(hists)