使用ggplot2和RColorBrewer为数据点着色

时间:2019-07-26 09:27:56

标签: r ggplot2

我有一个df,它具有超过400个数据点,并且想用RColorBrewer为那些palette = "Blues"包中的内容着色。

我绘制了数据,甚至将palette的颜色输入最大值扩展到了数据点的长度,以避免出现“错误消息”(见下文),但是图中的颜色没有改变(只有黑线)。

  

错误:美学的长度必须为1或   与数据(427)相同:填充

我创建了一个dummy df以使我的问题可以重现:

library(ggplot2)
library(RColorBrewer) 

color = colorRampPalette(rev(brewer.pal(n = 9, name = "Blues")))(300)

df = (curve(3*x^2 + x, from=1, to=10, n=300, xlab="xvalue", ylab="yvalue", 
         col="blue", lwd=2, main="Plot of (3x^2 + x)"))
dfx = matrix(data = df$x, ncol = 1)
dfy = matrix(data = df$y, ncol = 1)
dfa = cbind(dfx,dfy)

DF = ggplot(dfa, aes(x = dfx, y = dfy)) +
      geom_point(fill = color)

我希望曲线在开始时(1,4)变为浅蓝色,并随着黑暗的增加而增加,直到结束时(结束时为深蓝色(10,310))。

谢谢!

2 个答案:

答案 0 :(得分:2)

color_seq = colorRampPalette(brewer.pal(n = 9, name = "Blues"))(300)

df = (curve(3*x^2 + x, from=1, to=10, n=300, xlab="xvalue", ylab="yvalue", 
            col="blue", lwd=2, main="Plot of (3x^2 + x)"))
dfx = matrix(data = df$x, ncol = 1)
dfy = matrix(data = df$y, ncol = 1)
dfa = as.data.frame(cbind(dfx , dfy, color_seq), stringsAsFactors = FALSE)

dfa$V1 <- as.numeric(dfa$V1)  ## convert both to numeric so the scale is continous
dfa$V2 <- as.numeric(dfa$V2)

ggplot(dfa, aes(x = V1, y = V2, color = color_seq)) +
  geom_point() +
  scale_color_identity() 

答案 1 :(得分:1)

exDF <- data.frame(dataX = seq(1, 10, .1),
                   dataY = sapply(seq(1, 10, .1), function(x) 3*x^2 + x))

exDFcolors <- colorRampPalette(brewer.pal(9, "Blues"))(nrow(exDF))

ggplot(exDF, aes(dataX, dataY)) +
  geom_line(size = 2, color = exDFcolors)

enter image description here