当stat_smooth的aes恒定时如何在ggplot中添加图例

时间:2019-06-12 04:05:18

标签: r ggplot2 legend

我试图在一个图中绘制不同的平滑度:

ggplot(mtcars, aes(x=wt, y = mpg, col="green")) + 
  geom_point(col='blue') +
  stat_smooth(method='loess',linetype="dashed", col="red", span=0.1) +
  labs(title = "Fitting Price ~ living space, span=0.1,0.25,0.5,0.75") +
  stat_smooth(method='loess',linetype="dashed", col="cyan", span=0.25) +
  stat_smooth(method='loess',linetype="dashed", col="green", span=0.5) +
  stat_smooth(method='loess',linetype="dashed", col="blue", span=0.75) 

我想在其中添加图例,以显示每条平滑线的颜色。有些答案是说要为aes添加颜色,但是我没有为每个aes单独添加stat_smooth,并向col中添加aes ggplot无效。

2 个答案:

答案 0 :(得分:1)

我不知道从ggplot调用中创建的图层中添加图例的方法。另一种方法是预先计算平滑并以长格式将其馈入ggplot。

在这里,我定义了一个函数,用于根据输入范围生成一条拟合的黄土曲线,然后用其中的一些增加Tests-iMac:~ testautomation$ mvn -version Apache Maven 3.6.1 (d66c9c0b3152b2e69ee9bac180bb8fcc8e6af555; 2019-04-05T06:00:29+11:00) Maven home: /usr/local/Cellar/maven/3.6.1/libexec Java version: 1.8.0_212, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_212.jdk/Contents/Home/jre Default locale: en_AU, platform encoding: UTF-8 OS name: "mac os x", version: "10.14.5", arch: "x86_64", family: "Mac" ,然后收集成整齐(长)的形状,并馈入ggplot:

mtcars

enter image description here

答案 1 :(得分:0)

您仍然可以在每个aes中使用stat_smooth,仅包含所需的颜色。这将在图例中添加图例。然后,您可以使用scale_color_identity来匹配和重命名颜色

ggplot(mtcars, aes(x=wt, y = mpg, col="green")) + 
  geom_point(col='blue') +
  stat_smooth(method='loess',linetype="dashed", aes(color = "red"), span=0.1) +
  stat_smooth(method='loess',linetype="dashed", aes(color = "orange"), span=0.25) +
  stat_smooth(method='loess',linetype="dashed", aes(color = "yellow"), span=0.5) +
  stat_smooth(method='loess',linetype="dashed", aes(color = "green"), span=0.75) +
  labs(title = "Fitting Price ~ living space, span=0.1, 0.25, 0.5, 0.75") +
  scale_color_identity(name = "Span values",
                          breaks = c("red", "orange", "yellow", "green"),
                          labels = c("0.1", "0.25", "0.5", "0.75"),
                          guide = "legend")

更多信息,请访问Creating legends when aesthetics are constants in ggplot2