【问题标题】:Colouring of datapoint with ggplot2 and RColorBrewer使用 ggplot2 和 RColorBrewer 对数据点进行着色
【发布时间】:2019-07-26 09:27:56
【问题描述】:

我有一个带有 400 多个数据点的 df,我想用 palette = "Blues"RColorBrewer 包着色。

我绘制了我的数据,甚至将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))。

提前致谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:
    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() 
    

    【讨论】:

      【解决方案2】:
      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)
      

      【讨论】:

      • 这个函数和它的结合只是为了创建df。我正在使用不同的数据来制作我的情节。如果你编辑我的“DF”代码,你能给我一个例子吗?你的颜色看起来和我想要的完全一样,所以已经谢谢你了!
      猜你喜欢
      • 2013-07-15
      • 2021-08-16
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 2012-09-07
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多