【发布时间】:2016-05-08 14:24:27
【问题描述】:
我正在尝试使 ggplot 的图例键填充透明。我按照 Hadley 的 ggplot2 指南之一的说明更改了图例键填充,但由于某种原因,当我将填充设置为透明时,它会填充为灰色。即使我将图例键填充设置为白色,它在最终绘图中仍然显示为灰色。
这是一个例子:
library(ggplot2)
data1 = c(0,10, 11, 23, 33, 40, 41, 50, 59, 68, 76, 88, 90, 99)
data2 = c(2, 8, 10, 22, 39, 47, 49, 55, 62, 70, 76, 86, 88, 95)
df = data.frame(data1, data2)
(plot = ggplot() +
geom_smooth(data=df, aes(data1, data2,colour="sample1"))+
geom_abline(intercept=0, slope=1,linetype="dashed", color = "black")+
scale_x_continuous(expand=c(0,0), limits=c(0,100)) +
scale_y_continuous(expand=c(0,0), limits=c(0,100))+
theme_classic()+
labs(y="data2", x="data1",
title="sample 1 data1 vs data2") +
theme(plot.title = element_text(size=18, face="bold"),
legend.key = element_rect(colour = "transparent", fill = "white"),
legend.justification = c(1,0), legend.position = c(1,0))+
scale_color_discrete(name="Sample") )
如果我设置 theme(legend.key = element_rect(colour = "transparent", fill = "red")) 我得到以下情节:
看来我可以更改图例键填充,但不能更改为白色或透明色。
有谁知道我做错了什么,或者如果没有办法让图例键填充透明/白色?
编辑:设置theme(legend.key = element_rect(fill = alpha("white", 0.0))) 不能解决问题。
请看这里:
library(ggplot2)
library(scales)
data1 = c(0,10, 11, 23, 33, 40, 41, 50, 59, 68, 76, 88, 90, 99)
data2 = c(2, 8, 10, 22, 39, 47, 49, 55, 62, 70, 76, 86, 88, 95)
df = data.frame(data1, data2)
(plot = ggplot() +
geom_smooth(data=df, aes(data1, data2,colour="sample1"))+
theme_classic()+
labs(y="data2", x="data1",
title="sample 1 data1 vs data2") +
theme(plot.title = element_text(size=18, face="bold"),
legend.key = element_rect(colour = "transparent", fill = alpha("red", 0)),
legend.justification = c(1,0), legend.position = c(1,0))+
scale_color_discrete(name="Sample") )
EDIT2:如果我使用geom_line() 而不是geom_smooth 我可以将图例键填充设置为NA,所以这一定是因为geom_smooth 中的行有一个灰色区域作为置信区间在它周围,因此传说中的钥匙反映了它的外观。
(plot = ggplot() +
geom_smooth(data=df, aes(data1, data2,colour="sample1"))+
geom_abline(intercept=0, slope=1,linetype="dashed", color = "black")+
scale_x_continuous(expand=c(0,0), limits=c(0,100)) +
scale_y_continuous(expand=c(0,0), limits=c(0,100))+
theme_classic()+
labs(y="data2", x="data1",
title="sample 1 data1 vs data2") +
theme(plot.title = element_text(size=18, face="bold"),
legend.key = element_rect(colour = NA, fill = NA),
legend.justification = c(1,0), legend.position = c(1,0))+
scale_color_discrete(name="Sample") )
【问题讨论】:
-
设置
legend.key = element_rect(fill = NA)得到与以前相同的结果。键填充仍然是灰色的。 -
@VermillionAzure 在我的编辑中,我解释了为什么您提供的链接中的解决方案在这种情况下不起作用。
-
如果您将 se = FALSE 添加到您的 geom_smooth() 表达式中,您的代码就可以工作。所以你在传说中看到的是信心带
-
我自己才意识到这一点。我意识到如果我使用 geom_line() 而不是 geom_smooth() 那么我可以将填充设置为 NA。我想我可以忍受没有信心带,但我不能同时拥有这太糟糕了!感谢您的洞察力。编辑:啊,但是使用 geom_line() 不适用于我的实际数据集,因为它没有被平滑,所以我将使用你的解决方案来设置 se=FALSE