【问题标题】:Incorrect linetype in legend, ggplot2 in R图例中的线型不正确,R 中的 ggplot2
【发布时间】:2014-08-11 22:46:23
【问题描述】:

我在 R 中创建了一个 ggplot2 图,其中一条线伴随着一个阴影置信区间。但是,图例显示了错误的颜色和符号。使用 scale_size_manual 似乎无法解决问题。

剧情:

输入数据:

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

创建情节的代码:

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("")

是否有手动覆盖选项来更改绘图和图例的线型和颜色,而无需向熔化的数据框添加其他信息?

【问题讨论】:

  • 您对绘图区域的限制实际上没有任何意义。 value 变量的范围是 [-20, 20] 但你有:ylim = c(-0.75, 1)。 xlim 范围内存在相应的不匹配。当你把它们拿出来时,你会看到一个看起来像上面显示的图,但唯一指定的颜色是黑色(“#000000”),这就是线条的颜色。字符值“响应的 SD”与任何变量都不匹配,所以我想知道您是否认为 ggplot2 函数具有某种千里眼?
  • xlim 和 ylim 是我使用真实(专有)数据留下的。当我移除它们时,它们对颜色没有影响。

标签: r ggplot2


【解决方案1】:

你会发现不使用融化的数据会容易得多。

同时引用Remove extra legends in ggplot2

美学可以在 ggplot 调用中设置或映射。

  • 在 aes(...) 中定义的美学是从数据中映射出来的,并创建了一个图例。
  • 美学也可以设置为单个值,方法是在 aes() 外部定义它。

因此类似于

 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_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') 

【讨论】:

  • 这仍然没有黑线的图例。当使用不同的绘图类型(geom_ribbon 和 geom_line)时,ggplot2 不能实现这一点吗?
  • @fifthace -- 第二个选项为您提供了使用方法- 可能需要代表您进行一些思考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 2013-12-21
  • 1970-01-01
相关资源
最近更新 更多