【问题标题】:Colour points in a plot differently depending on a vector of values绘图中的颜色点因值向量而异
【发布时间】:2018-08-28 14:43:52
【问题描述】:

我正在使用 R 的 plot() 函数绘制下图。它是一个向量shiftTime 的时间偏移图。我有另一个向量intensity 的强度值范围从 ~3 到 ~9。我想根据这些具有颜色渐变的值在图中为我的点着色。我可以在实际绘制点的值上找到颜色的示例,因此在这种情况下,向量shiftTime 的值。是否也可以使用不同的向量,只要对应的值在同一个索引上?

【问题讨论】:

    标签: r colors plot gradient


    【解决方案1】:

    这是使用基本 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)
    

    【讨论】:

    • 我觉得这可能相当直观,但为了澄清一下,调色板中使用的“10”是指该范围内的颜色数量。这甚至可以被分离出来并分配给一个变量以获得更可配置的图表。
    • 这对于连续增加的数据来说很好,但是如果一个点低于前一个点呢?这种颜色编码不会显示出来。
    • 对不起那个joran
    【解决方案2】:

    使用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")
    

    【讨论】:

      【解决方案3】:

      在基础 R 中为 joran 的答案添加图例:

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

      本例添加“,cex=0.8”只是为了美观:

      【讨论】:

      • 你如何让这个图例成为一个连续的颜色渐变条?
      • 如何在参数图例中使用正确的值? (不是图例=c(1:10))??
      • 使用cut(dat$y,breaks = 10) 获取参数图例中的正确值
      【解决方案4】:

      colorRamp() 返回一个函数,用于为 0:1 区间内的数字分配颜色。

      pal <- colorRamp(c("blue", "green", "orange", "red"))
      

      现在rgb() 可以用来从这个函数中得到一个可用的颜色:

      rgb(pal(0.5), max=255)
      [1] "#7FD200"
      

      因此,如果将向量转换为 0-1 范围,则可以使用 pal() 进行颜色分配。

      完整演示:

      x <- rnorm(1000)
      
      # NOTE: (x-min(x)) / diff(range(x)) transforms x to have a range of 0:1
      pal <- colorRamp(c("blue", "green", "orange", "red"))    # 1) choose colors
      col <- rgb(pal((x - min(x)) / diff(range(x))), max=255)  # 2) interpolate numbers
      
      plot(x, col=col, pch=19)
      

      【讨论】:

        猜你喜欢
        • 2011-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-26
        • 2018-04-08
        • 2023-03-17
        • 1970-01-01
        相关资源
        最近更新 更多