根据值的向量,绘图中的颜色点不同

Nie*_*ein 45 plot gradient r colors

我正在使用R的绘图功能绘制下面的图.它是时间偏移的矢量'shiftTime'的图.我有另一个强度值的矢量'强度',范围从~3到~9.我想基于具有颜色渐变的那些值在绘图中为我的点着色.我可以在实际绘制点的值上找到颜色的示例,因此在这种情况下,矢量'shiftTime'的值.是否也可以使用不同的向量,只要相应的值在同一个索引上?

我的情节

jor*_*ran 107

这是使用基础R图形的解决方案:

#Some sample data
x <- runif(100)
dat <- data.frame(x = x,y = x^2 + 1)

#Create a function to generate a continuous color palette
rbPal <- colorRampPalette(c('red','blue'))

#This adds a column of color values
# based on the y values
dat$Col <- rbPal(10)[as.numeric(cut(dat$y,breaks = 10))]

plot(dat$x,dat$y,pch = 20,col = dat$Col)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 这很棒!我将如何展示它的传奇? (6认同)

ROL*_*OLO 20

使用ggplot2的解决方案:

library(ggplot2)

#Some sample data
x <- sort(runif(100))
dat <- data.frame(x = x,y = x^2 + 1)
# Some external vector for the color scale
col <- sort(rnorm(100))

qplot(x, y, data=dat, colour=col) + scale_colour_gradient(low="red", high="blue")
Run Code Online (Sandbox Code Playgroud)

情节


pur*_*mac 17

要在基础R中为joran的答案添加图例:

legend("topleft",title="Decile",legend=c(1:10),col =rbPal(10),pch=20)
Run Code Online (Sandbox Code Playgroud)

这个例子只是为了美观而添加",cex = 0.8":

多彩的情节包括传奇

  • 你如何让这个图例成为一个连续的颜色渐变条? (2认同)