2012-03-30 33 views
34

我使用R的繪圖函數繪製下圖。它是時間轉移的向量'shiftTime'的圖。我有另一個向量'強度'的強度值範圍從〜3到〜9。我想用顏色漸變爲基於這些值的點繪圖。我可以在實際繪製點的值上找到顏色的示例,因此在這種情況下,矢量'shiftTime'的值。只要相應的值在同一個索引上,是否也可以使用不同的向量?根據值的向量,情節中的顏色點會有所不同

My plot

回答

89

下面是使用鹼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) 

enter image description here

+4

這是偉大的!我將如何顯示圖例? – 2015-07-13 22:16:46

16

解決方案使用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") 

plot

12

要將傳說添加到joran的回答在基礎R:

legend("topleft",title="Decile",legend=c(1:10),col =rbPal(10),pch=20) 

本示例添加」,CEX = 0.8" 只是順其自然:

multicoloured plot including legend

+0

你會如何讓這個傳說變成一個連續的顏色淡化吧? – colin 2017-01-04 21:39:26

+0

如何在參數圖例中使用正確的值? (不是傳說= c(1:10))?? – xhie 2017-05-12 18:49:13