[英]Legend for lines but not fill ggplot2
我正在使用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)
這是沒有圖例的當前外觀。 我想要這樣,但有一個垂直線的圖例: 有什么建議么? 謝謝!
嘗試修改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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.