【问题标题】:Coloring the points in a plot based on another numeric variable根据另一个数值变量为绘图中的点着色
【发布时间】:2014-09-20 00:17:52
【问题描述】:

我正在绘制“wt”与“mpg”(来自“mtcars”数据集),现在我想根据“hp”为点着色。 我想采用绿色并缩放其阴影,因此高“hp”值将变为深绿色,而低值将变为淡绿色。

没有颜色的基础图:

data(mtcars)
plot <- with(mtcars, {
  plot(wt, mpg, xlab="Weight", ylab="Miles per Gallon")
})

在 R-Base 中最简单的方法是什么?那么ggplot2/lattice呢?

【问题讨论】:

    标签: r colors plot


    【解决方案1】:

    使用这样的东西:

    library(ggplot2)   
    ggplot(mtcars, aes(x=wt, y=mpg))+geom_point(aes(col=hp))
    

    将颜色更改为您想要的颜色。也许thisthis 可以提供帮助。

    【讨论】:

      【解决方案2】:

      查看classInt 包。它提供了几种将数值变量hp 转换为区间的方法。包RColorBrewer 提供了合理的调色板。例如,

      library(classInt)
      library(RColorBrewer)
      n <- 5 # number of levels 
      hp_ints <- classIntervals(mtcars[, "hp"], n, style="quantile") 
      # other options for style include "fixed", "sd", "equal", "pretty", "quantile", "kmeans", "hclust", "bclust", "fisher", or "jenks"
      pal <- brewer.pal(n, "Greens")
      hp_col <- pal[findInterval(mtcars[, "hp"], hp_ints$brks, all.inside=TRUE)]
      plot(mpg~wt, data=mtcars, col=hp_col, pch=19)
      

      【讨论】:

      • 为了完整起见,可以在基础 R 中使用 cut 完成同样的事情。
      【解决方案3】:

      基础 R

      您可以使用colorRamp 创建一个返回绿色阴影的函数:

      cr <- colorRamp(c("green", "black"))
      

      然后你可以使用:

      with(mtcars, {
          plot(wt, mpg, col = rgb(cr(hp / max(hp)), max=255),
               xlab="Weight", ylab="Miles per Gallon", pch=20)
      })
      

      cr 接受 0 到 1 之间的值,这就是我除以 max(hp) 的原因

      ggplot2

      p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(aes(col = hp))
      p + scale_colour_gradientn(colours=c("green","black")) + theme_bw()
      

      希望对你有帮助,

      亚历克斯

      【讨论】:

      • 谢谢,亚历克斯!非常好。
      猜你喜欢
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多