[英]Add simple histogram to legend in ggplot2
給定使用以下代碼生成的ggplot
plot
size = 10000
d = data.frame(
type = rep(c("A","B","C"), each=size),
val = c(rnorm(size, 0, 1), rnorm(size, 1, 2),rnorm(size, 2, 3))
)
require(ggplot2)
(
ggplot(subset(d, is.element(type, c("A", "C"))), aes(x=val))
+ geom_histogram(aes(y=..density..), bins=100, position="identity", alpha=0.5)
+ geom_line(aes(color=type), stat="density", size=1)
)
是否可以使用代表簡單直方圖的自定義 label 添加一個灰色方塊? 可以在不創建虛擬項目的情況下完成嗎?
您只需將fill=
放入geom_histogram()
行的aes()
中。 您的數據集中沒有要分配給它的列,但是如果您在aes()
中分配fill="string name"
,那么ggplot
將創建一個填充圖例,其名稱為 label。
當然,顏色將默認為ggplot
"red" 顏色,因此如果您想再次將 go 設置為灰色,則必須使用scale_fill_manual()
進行設置,因為fill=
outside aes()
將覆蓋您放入aes()
.
ggplot(d, aes(x=val)) +
geom_histogram(aes(y=..density.., fill='histogram'),
bins=100, position="identity", alpha=0.5) +
geom_line(aes(color=type), stat="density", size=1) +
scale_fill_manual(values='gray20')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.