如何让 R plotly 为不同的线段使用不同的颜色

How to get R plotly to use different colors for different line segments

如果 g 是一个 factor 变量,我可以使以下内容起作用,但我希望连续处理颜色。当我运行下面的时候,颜色被忽略了——线段都是蓝色的。

require(plotly)
x <- rep(c(1, 1, NA,  2, 2, NA, 3, 3, NA), 2)
y <- c(1, 2, NA, 2, 3, NA, 3, 4, NA, 11, 12, NA, 12, 13, NA, 13, 14, NA)
g <- c(rep(1, 9), rep(2, 9))
plot_ly(x=x, y=y, type='lines', color=g)

有一个使用 ggplot2plotly::ggplotly 的解决方案,但我宁愿找到一个全 plotly 解决方案:

g <- ggplot(data) + geom_segment(aes(x=x, xend=x2, y=y, yend=y2, color=z)
ggplotly(g)

虽然 plotly 似乎对将颜色映射到标记有相当多的支持,但它似乎对线条的支持很少,因此您必须提供它。下面设置调色板和 g 值之间的映射,然后创建一个带有线条颜色的 plotly 对象和对应于调色板映射的颜色条。

  library(plotly)
  library(RColorBrewer)
  df <- data.frame(x=x, y=y, g=g)
# 
#  Seclect a color palette from the ColorBrewer palettes
   num_colors <- 8
   color_pal <- brewer.pal(num_colors, "RdYlBu")
#  Make a plotly colorscale for the palette  
   g_colorscale <- data.frame( seq(0,1, 1/(num_colors-1)), color_pal)
   colnames(g_colorscale) <- NULL
#  Set the min and max for mapping g values to colors    
   gmin <- min(df$g)-.5
   gmax <- max(df$g)+.5
#  Create an interpolation function for mapping g values to colors 
   color_rmp <- colorRamp(color_pal)
   g_color_map <- function(g, gmin,  gmax) {
                        g_3color <- as.vector(color_rmp((g - gmin)/(gmax-gmin)))/255 
                        rgb(g_3color[1],g_3color[2], g_3color[3]) 
   }
# Create plotly object with a colorbar    
  sp <- plot_ly(data=df, x=x, y=y, type="scatter", mode="markers", 
                 showlegend=FALSE, 
                 marker=list(colorscale=g_colorscale,
                             colorbar=list(title="g"),
                             cmin=gmin, cmax=gmax , size=1))
# Add a line for each g value
  for( g_line in unique(df$g)) {
    sp <- add_trace(sp, data=df[df$g==g_line,], x=x, y=y, 
                   type="scatter", mode="lines", inherit=FALSE, showlegend=FALSE,
                   name=g_line, evaluate=TRUE, 
                   line=list(width=5, dash="solid",
                             color=g_color_map(g_line, gmin=gmin, gmax=gmax)))
  }
# Add chart features  
  sp <- layout(sp, xaxis = list(range=c(.5,3.5)))

给出图表

我的印象是 plotly 是一个较低级别的绘图包,对于更复杂的图表,在 ggplot 中开发图表然后转换为 [=11 可能更直接=] 对象而不是直接在 plotly 中开发。将您的 ggplot 解决方案与上面给出的本机 plotly 方法进行比较就是一个例子。