通过超过2种定义颜色的渐变填充或连续缩放颜色

时间:2017-02-16 10:22:56

标签: r ggplot2

是否可以通过低于和高定义的参数来制作颜色渐变?

让我们说,关于这些数据:

df <- data.frame(a = 1:100, 
                 b = rnorm(100, mean = 1000, sd = 500))
ggplot(df) +
   geom_point(aes(a, b)) +
   scale_fill_continous(low = "white", high = "black")
         ## as "low" and "high" is all scale_fill_continous() funcion offer

设置低参数和高参数只会产生线性颜色渐变,但我想要更多的组合颜色渐变,让我们说从白色到蓝色再到黑色。

感谢您的关注和答案。

3 个答案:

答案 0 :(得分:3)

您可以尝试:

set.seed(123)
df <- data.frame(a=1:100, b=rnorm(100, mean = 1000, sd = 500))
ggplot(df,aes(x=a, y=b, col=b)) + geom_point() +  
  scale_colour_gradientn(colours = c("green", "blue","blue", "red","red", "yellow"),breaks = c(0,1000,2000,3000), limits=c(0,3000))

enter image description here

答案 1 :(得分:1)

ggplot(data.frame(x=seq(along=x), y=rnorm(100, mean = 1000, sd = 500)), aes(x=x, y=y, colour=y)) + 
geom_point() + 
scale_colour_gradientn(values=c(0, 1000, 2000, 3000),
colours=c("green", "blue", "red", "yellow"),
rescaler=function(x, ...) x, oob=identity)

给出这个情节

plot

答案 2 :(得分:1)

colorpanel中的gplots功能非常适用于此。它产生2种或3种颜色之间的n种颜色(例如50)的光谱(中间颜色是可选的):

library("gplots")
scale_fill_continuous <- colorpanel(50, "blue", "red") #2 colours
scale_fill_continuous <- colorpanel(50, "blue", "white", "red") #3 colours

还有各种预设功能,例如rainbow(50)greenred(50)(中=黑)或bluered(50)(中=白)。

对于给出的例子:

#Generate a colour spectrum
library("gplots")
scale_fill_continuous <- colorpanel(300, "green", "purple", "yellow") 
#Generate data
set.seed(5)
data <- rnorm(100, mean = 1000, sd = 500)
mapping <- ceiling(data/100) #round to index in colour scale
coloured_data <- scale_fill_continuous[mapping] #map to colour sale