[英]Incorrect linetype in legend, ggplot2 in R
I have created a ggplot2 plot in R where a line is accompanied by a shaded confidence interval. 我在R中创建了一个ggplot2图,其中一条线带有阴影的置信区间。 However, the legend shows the wrong colour and symbol.
但是,图例显示了错误的颜色和符号。 Using scale_size_manual does not seem to correct the issue.
使用scale_size_manual似乎无法解决此问题。
The plot: 剧情:
The input data: 输入数据:
my_example_data <- data.frame(Price = c(5,0,-5), Consumption = c(20,0,-20), Lower = c(17,-3,-21), Upper = c(21, 2, 23))
my_example_data.melt <- melt(my_example_data, id = "Price")
Price variable value
1 5 Consumption 20
2 0 Consumption 0
3 -5 Consumption -20
4 5 Lower 17
5 0 Lower -3
6 -5 Lower -21
7 5 Upper 21
8 0 Upper 2
9 -5 Upper 23
The code to create the plot: 创建图的代码:
ggplot(subset(my_example_data.melt, variable == "Consumption"), aes(Price,value,fill='Mean response'), linetype=1) +
geom_line(colour="#000000") +
coord_cartesian(xlim = c(-100, 100),ylim = c(-0.75, 1)) +
geom_ribbon(aes(ymin = subset(my_example_data.melt, variable == "Lower")$value, ymax = subset(my_example_data.melt, variable == "Upper")$value,fill = 'SD of response'),alpha=0.3, colour=NA) +
xlab("Change in relative price [Δ€]") +
ylab("Change in consumption [MW]") +
theme(legend.position="bottom", legend.direction="horizontal") +
xlab("Change in relative price [Δ€]") +
ylab("Change in consumption [MW]") +
scale_fill_discrete("")
Is there a manual override option for changing the linetypes and colour for the plot and legend without having to add additional information to the melted dataframe? 是否有一个手动覆盖选项,用于更改图和图例的线型和颜色,而不必向融化的数据框中添加其他信息?
You will find this much easier not using the melted data. 您将发现不使用合并的数据会容易得多。
Also quoting from Remove extra legends in ggplot2 , 还引用了删除ggplot2中的多余图例 ,
Aesthetics can be set or mapped within a ggplot call. 可以在ggplot调用中设置或映射美学。
Therefore something like 因此类似
ggplot(my_example_data,aes(x=Price)) +
geom_ribbon(aes(ymin=Lower,ymax=Upper),fill='blue',alpha=0.5) +
geom_line(aes(y=Consumption))
or perhaps If you really wanted a legend, you could use scale_identity
或者,如果您确实想要图例,则可以使用
scale_identity
ggplot(my_example_data,aes(x=Price)) +
geom_ribbon(aes(ymin=Lower,ymax=Upper,fill='blue'), alpha=0.5) +
geom_line(aes(y=Consumption)) +
scale_fill_identity(guide='legend', name = 'Your name', label = 'whatever')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.