【问题标题】:ggplot2: solid line for one group, points for the otherggplot2:一组实线,另一组点
【发布时间】:2018-11-02 12:21:09
【问题描述】:

我有四个系列想要绘制。
有 2 个模型:xg 和 algo30。 有两种类型的数据:预测数据和观察数据。
这意味着我们有以下 4 个系列:“predicted xg”、“observed xg”、“predicted 30”、“observed 30”。

我希望“xg”为蓝色,“algo30”为红色。 我还希望预测为实线并观察为点。

这就是我的意思,使用基础图:

library(magrittr)
library(ggplot2)
library(dplyr)

set.seed(123)
gr <- 1:10
obs.xg <- sort(runif(10, 0.5, 1))
obs.30 <- sort(runif(10, 0.5, 1))
pred.xg <- lm(obs.xg~gr) %>% predict() %>% add(rnorm(10,0,.01))
pred.30 <- lm(obs.30~gr) %>% predict() %>% add(rnorm(10,0,.01))        
plot(gr, obs.xg, col="darkblue", ylim=range(c(obs.xg,obs.30)), pch=20)
lines(gr, pred.xg, col="darkblue", lwd=2)
points(gr, obs.30, col="firebrick", pch=20)
lines(gr, pred.30, col="firebrick", lwd=2)
legend("bottomright", 
  pch=c(20,NA,NA,NA,NA),
  lty=c(NA,1,NA,1,1),
  lwd=c(NA,1,NA,2,2),
  col = c("black","black",NA, "darkblue","firebrick"),
  legend=c("observé","prédit",NA,"xgboost","algo30"),
  bty='n')

这是我使用 ggplot 的最佳尝试。请注意,图例无法按我的意愿工作。

xg.data <- data.frame(model= "xg", decile = seq(1:10), observed = obs.xg, predicted = pred.xg)
algo30.data <- data.frame(model = "algo30",decile = seq(1:10),  observed = obs.30, predicted = pred.30)
ggplotdata <- bind_rows(xg.data, algo30.data)

ggplotdata %>%
   ggplot( aes(x=decile, y= predicted, color= model))+ geom_line()+
  geom_point(aes(x=decile, y= observed, color = model))

【问题讨论】:

  • 别忘了在问题中包含你的包(我不知道add() 来自哪里)。
  • 我的错 - 我在复制粘贴时丢失了第一行。这是 magrittr::add
  • 基础 R 有什么问题? ;)

标签: r ggplot2


【解决方案1】:

大多数时候,在制作这样的传奇时,我会在 guide_legend() 中寻找 override.aes

这里的想法是使用您不希望映射到绘图本身的附加美学来制作图例,然后使用常量而不是变量来实现该美学。我使用了alpha,因为点和线都使用了这种美学。

然后在scale_alpha_manual 中完成繁重的工作:删除图例名称,通过设置values 确保绘图仍然正确,然后,最后选择正确的点类型和线以及空白传奇。

ggplot(ggplotdata, aes(x=decile, y= predicted, color= model))+ 
    geom_line( aes(alpha = "prédit") )+
    geom_point(aes(x=decile, y= observed, alpha = "observé")) +
    scale_alpha_manual(name = NULL, values = c(1, 1),
                       guide = guide_legend(override.aes = list(linetype = c(0, 1), shape = c(16, NA)))) +
    scale_color_manual(name = NULL, values = c("firebrick", "darkblue"))

【讨论】:

  • 我不知道 override.aes ,这正是我需要的,谢谢!我将稍微移动一下球门柱,并在此处添加有关如何从颜色图例中删除该点的快速说明: + scale_color_manual(name = NULL, values = c("firebrick", "darkblue"), guide = guide_legend(override .aes= list(shape = c(NA, NA)))) # 没意义
猜你喜欢
  • 2021-08-19
  • 2020-04-07
  • 2021-12-07
  • 1970-01-01
  • 2010-10-10
  • 2016-01-24
  • 1970-01-01
  • 2019-10-18
  • 2012-06-10
相关资源
最近更新 更多