在R中,有没有办法根据一系列数字为渐变上的绘图点着色?

时间:2021-03-29 15:00:10

I'm new to R, and I've been able to plot points, but wondering if there is a way to apply a color gradient to the scatterplot.

我是R的新手,我已经能够绘制点,但想知道是否有办法将颜色渐变应用于散点图。

I have a 3 column matrix, where the first two will be used as coordinates, and the third has range of numbers between 0 and .0001. Is there a way to color the plot points based on where they fall in the range of numbers?

我有一个3列矩阵,其中前两个将用作坐标,第三个具有0到0.0001之间的数字范围。有没有办法根据它们落在数字范围内的位置为绘图点着色?

 x   y   z
 15  3   6e-4
 34  22  1e-10
 24  1   5e-2
 ...

plot(x, y, main= "Title", ylab = "column y", xlab = "column x", col = rgb(0,100,0,50,maxColorValue=255), pch=16) 

3 个解决方案

#1


3  

I'm big on the ggplot2 package, because it does a lot to encourage good plotting habits (although the syntax is a bit confusing at first):

我对ggplot2包非常重视,因为它可以鼓励良好的绘图习惯(尽管语法起初有点令人困惑):

require(ggplot2)
df <- data.frame(x=x, y=y, z=z) #ggplot2 only likes to deal with data frames
ggplot2(df, aes(x=x, y=y, colour=z) + #create the 'base layer' of the plot
  geom_point() + #represent the data with points
  scale_colour_gradient(low="black", high="green") + #you have lots of options for color mapping
  scale_x_continuous("column x") + #you can use scale_... to modify the scale in lots of other ways
  scale_y_continuous("column y") +
  ggtitle("Title") 

#2


2  

How about

怎么样

plot(x, y, col = gray(z/0.0001)) 

This is by gray.

这是灰色的。

#3


0  

Late, but for benefit of others this may be what you were after:

迟到了,但为了别人的利益,这可能就是你所追求的:

mat = cbind(sample(1:30), sample(1:30), 10*rnorm(30,mean=5))
n = 255
data_seq = seq(min(mat[,3]), max(mat[,3]), length=n)
col_pal = colorRampPalette(c('darkblue','orange'))(n+1)
cols = col_pal[ cut(mat[,3], data_seq, include.lowest=T) ]
plot(mat[, 1:2], col = cols, pch=16, cex=2)

#1


3  

I'm big on the ggplot2 package, because it does a lot to encourage good plotting habits (although the syntax is a bit confusing at first):

我对ggplot2包非常重视,因为它可以鼓励良好的绘图习惯(尽管语法起初有点令人困惑):

require(ggplot2)
df <- data.frame(x=x, y=y, z=z) #ggplot2 only likes to deal with data frames
ggplot2(df, aes(x=x, y=y, colour=z) + #create the 'base layer' of the plot
  geom_point() + #represent the data with points
  scale_colour_gradient(low="black", high="green") + #you have lots of options for color mapping
  scale_x_continuous("column x") + #you can use scale_... to modify the scale in lots of other ways
  scale_y_continuous("column y") +
  ggtitle("Title") 

#2


2  

How about

怎么样

plot(x, y, col = gray(z/0.0001)) 

This is by gray.

这是灰色的。

#3


0  

Late, but for benefit of others this may be what you were after:

迟到了,但为了别人的利益,这可能就是你所追求的:

mat = cbind(sample(1:30), sample(1:30), 10*rnorm(30,mean=5))
n = 255
data_seq = seq(min(mat[,3]), max(mat[,3]), length=n)
col_pal = colorRampPalette(c('darkblue','orange'))(n+1)
cols = col_pal[ cut(mat[,3], data_seq, include.lowest=T) ]
plot(mat[, 1:2], col = cols, pch=16, cex=2)