R 基于另一个数值变量为绘图中的点着色

R 基于另一个数值变量为绘图中的点着色,r,colors,plot,R,Colors,Plot,我正在绘制“wt”和“mpg”(来自“mtcars”数据集),现在我想根据“hp”为点上色。 我想采用绿色并调整其色调,这样高“hp”值将变为深绿色,低值将变为淡绿色 不带颜色的底图: data(mtcars) plot <- with(mtcars, { plot(wt, mpg, xlab="Weight", ylab="Miles per Gallon") }) 数据(mtcars) 绘图使用如下方式: library(ggplot2) ggplot(mtcars, ae

我正在绘制“wt”和“mpg”(来自“mtcars”数据集),现在我想根据“hp”为点上色。 我想采用绿色并调整其色调,这样高“hp”值将变为深绿色,低值将变为淡绿色

不带颜色的底图:

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

绘图使用如下方式:

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

将颜色更改为所需的颜色。也许或者可以帮忙。

Base R

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

cr <- colorRamp(c("green", "black"))
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()

p看看
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)
库(classInt)
图书馆(RColorBrewer)

n为了完整性,我们可以用R底的
cut
完成同样的事情。谢谢你,亚历克斯!非常好。
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)