如何在R图形色标中强制将零映射到白色

时间:2017-04-19 20:06:41

标签: r graph colors plotly

我的代码如下,但我希望将白色映射到0而不是data_bydate $ avg_score的最大值和最小值的中间值

g <- plot_ly(data_bydate, x = ~Date, y = ~avg_score, color =data_bydate$avg_score, colors = c("#FF0000","#FFFFFF", "#008000"), mode ='markers', marker = list(size=3)) %>%
layout(legend = list(orientation = 'h'), 
       xaxis = list(title = "",
                    zeroline = FALSE,
                    tickformat="%X",
                    showline = TRUE), 
       yaxis = list(title = "",
                    zeroline = FALSE,
                    showline = TRUE ))

现在它没有给出一个图表,其中上述零值为绿色,零以下值为红色......

2 个答案:

答案 0 :(得分:1)

您可以创建自己的colorscale,从红色(最小)到白色(零)到绿色(最大)。 colorscale是一个数组列表,由两个独立的颜色标记组成,一个用于零下的部分,从红色到白色,另一个在上面,从白色到绿色。

enter image description here

library(plotly)
library(scales)

set.seed(42)
colorlength <- 100

data_bydate <- data.frame(Date = c(1:23),
                          avg_score = c(runif(10, -5, -1), 
                                        rep(0,3), 
                                        runif(10, 1, 10)
                                        )
                          )

null_value <- (0 - min(data_bydate$avg_score)) / (max(data_bydate$avg_score) - min(data_bydate$avg_score))        
border <- as.integer(null_value * colorlength)
colorscale <- as.list(1:colorlength)

#colorscale below zero
s <- scales::seq_gradient_pal("#FF0000", "#FFFFFF", "Lab")(seq(0,1,length.out=border))
for (i in 1:border) {
    colorscale[[i]] <- c((i - 1) / colorlength, s[i])
}

#colorscale above zero
s <- scales::seq_gradient_pal("#FFFFFF", "#008000", "Lab")(seq(0,1,length.out=colorlength - border))
for (i in 1:(colorlength - border)) {
  colorscale[[i + border]] <- c((i + border) / colorlength, s[i])
}

plot_ly(data_bydate, 
        x = ~Date, 
        y = ~avg_score, 
        type = 'scatter',
        mode ='markers', 
        marker = list(size = 10,
                      color = ~avg_score,
                      colorscale = colorscale,
                      colorbar = list(len=1))) %>%
  layout(plot_bgcolor = 'black')

答案 1 :(得分:0)

一个简单的方法是设置限制,这里 min 为 -2,max 为 2,0 为中间值。

colorbar(title = "Change (%)", limits = c(-2, 2))

并选择一个发散的调色板;

colorscale = "RdBu",
reversescale = TRUE,

发散的调色板是:BrBG、PiYG、PRGn、PuOr、RdBu、RdGy、RdYlBu、RdYlGn、Spectral。

反转比例会反转色阶的方向。