visreg 和 ggplot,如何通过渐变中的连续变量为点着色

问题描述 投票:0回答:1

我需要使用 visreg 显示模型,同时自定义顶部图层的颜色。 我使用空气质量数据集作为示例。这是我创建 visreg 图层的代码,我想在其中可视化不同级别风的模型。绘制它时,根据第三个数值变量的点的颜色减少到 2。

visreg(fit,"Solar.R","Wind",
          overlay=TRUE,breaks = 2,gg=TRUE)+
     scale_color_manual(values = c("#90da90", "red3"))+
     scale_fill_manual(values = c("gray", "gray"))+
     theme_minimal()

即使我想要我的线具有两个风值,我希望我的点以风的梯度着色,以反映原始值,这些点应该如下所示:

 ggplot(airquality, aes(x=Solar.R,y=Ozone,color=Wind))+
      geom_point()+
      scale_color_gradient(low = "#90da90", high = "red3")+
      theme_minimal()

但我不能让这两件事在同一个情节中工作

我有过几次不成功的尝试,大部分都是这种类型

 visreg(fit,"Solar.R","Wind",
           overlay=TRUE,breaks = 2,gg=TRUE,
           partial=FALSE,rug=FALSE)+
      scale_color_manual(values = c("#90da90", "red3"))+
      scale_fill_manual(values = c("gray", "gray"))+
      geom_point(aes(color=Wind))+  
      scale_color_gradient(low = "#90da90", high = "red3")+
      theme_minimal()

但不知何故,我得到了与第三个变量的规模相关的错误

有人知道该怎么做吗?拜托,我的想象力已经耗尽了。

r ggplot2 plot gradient visreg
1个回答
0
投票

第一个问题是,在

visreg
对象中,
Wind
是一个
factor
,而“原始”值包含在名为
y
的列中,即在
color = y
中使用
geom_point
。其次,在香草
ggplot2
中,每种审美只能有一个尺度,而且这个尺度要么是离散的,要么是连续的。为了克服这个问题,您可以使用
ggnewscale
包,它允许具有多个比例以获得相同的美感。

此外,在下面的代码中我添加了两个调整。首先,我删除了已经存在的

geom_point
层,其次我最终切换了点层和线层的顺序,将线放在顶部。但如果这对您来说不重要,您可以删除这两行代码。

library(visreg)
library(ggplot2)
library(ggnewscale)

fit <- lm(Ozone ~ Solar.R + Wind + Temp, data = airquality)

p <- visreg(fit, "Solar.R", "Wind",
  overlay = TRUE, breaks = 2, gg = TRUE
) +
  scale_color_manual(values = c("#90da90", "red3")) +
  scale_fill_manual(values = c("gray", "gray")) +
  theme_minimal()
#> Scale for colour is already present.
#> Adding another scale for colour, which will replace the existing scale.
#> Scale for fill is already present.
#> Adding another scale for fill, which will replace the existing scale.

# Get rid of default points layer (You can drop that)
p$layers[[2]] <- NULL

p <- p +
  ggnewscale::new_scale_color() +
  geom_point(aes(color = y)) +
  scale_color_gradient(
    name = "Wind",
    low = "#90da90", high = "red3"
  )

# Switch order of layers to put lines on top  (You can drop that)
p$layers <- p$layers[c(1, 3, 2)]

p

© www.soinside.com 2019 - 2024. All rights reserved.