首页 > 解决方案 > Plotly:如何为每个数据设置背景颜色

问题描述

我想设置两种不同的颜色作为绘图背景:每个数据一种颜色,像这样

参考图表

到目前为止,这是我的情节:

我的图表

标签: rplotplotlyr-plotly

解决方案


以下建议是一个最小的可重现示例,向您展示它可以完成。尽管不像您希望的那样容易和优雅。据我所知,目前还没有一种方法可以在不通过shape的情况下交替背景颜色。以下设置至少捕获了您演示设置的一些功能,因为它是折线图和条形图的混合,并且一次生成多个子图。

阴谋:

在此处输入图像描述

代码:

library(dplyr)
library(plotly)

df = data.frame(x=c(1,2,3,4,5,6,7,8,9,10,11,12),
                y1=c(4,2,4,2,6,7,8,7,9,10,9,12),
                y2=c(3,4,5,6,3,1,5,6,3,2,7,8))


list(df$x)

x_start <- df$x[seq(1, length(df$x), 2)]
x_stops <- df$x[seq(2, length(df$x), 2)]

p1 <- plot_ly(x=df$x, y=df$y1, mode='lines', line=list(color='green'), name = 'line')
p2 <- plot_ly(df) %>% add_bars(x=~x, y=~y2, name='bar', width=0.4)

# set up shapes
shape=list(type='rect', line = list(color = 'rgba(0,0,0,0)'), fillcolor="rgba(147,112,219,0.1)", xref='x', yref='y')
shape_offset = 0.5
shapes <- list()

for (i in seq_along(x_start)){
  print(i)
  shape[["x0"]] <- x_start[i] + shape_offset
  shape[["x1"]] <- x_stops[i] + shape_offset
  shape[["y0"]] <- 0
  shape[["y1"]] <- 16
  shapes <- c(shapes, list(shape))
}

p1 <- layout(p1, shapes=shapes, xaxis = list(showgrid=FALSE))                 
p2 <- layout(p2, shapes=shapes)                 


p <- subplot(p1, p2, nrows = 2, margin=0.05)

p

我希望这对你有用。如果您愿意,我们可以在您有机会查看时讨论更多细节。

编辑1:

这是一个建议,在构建背景形状时考虑了 y 的最大值。如果您有兴趣,可以灵活调整子图的数量。

情节2:

在此处输入图像描述

代码 2:

library(dplyr)
library(plotly)

df = data.frame(x=c(1,2,3,4,5,6,7,8,9,10,11,12),
                y1=c(4,2,4,2,6,7,8,7,9,10,9,12),
                y2=c(3,4,5,6,3,1,5,6,3,2,7,8))


list(df$x)

x_start <- df$x[seq(1, length(df$x), 2)]
x_stops <- df$x[seq(2, length(df$x), 2)]

p1 <- plot_ly(x=df$x, y=df$y1, mode='lines', line=list(color='green'), name = 'line')
p2 <- plot_ly(df) %>% add_bars(x=~x, y=~y2, name='bar', width=0.4)

# set up plot 1 shapes
shape=list(type='rect', line = list(color = 'rgba(0,0,0,0)'), fillcolor="rgba(147,112,219,0.1)", xref='x', yref='y')
shape_offset = 0.5

shapes <- list()


for (i in seq_along(x_start)){
  print(i)
  shape[["x0"]] <- x_start[i] + shape_offset
  shape[["x1"]] <- x_stops[i] + shape_offset
  shape[["y0"]] <- 0
  shape[["y1"]] <- max(df$y1)
  shapes <- c(shapes, list(shape))
  #print()
}

# set up plot 2 shapes
shape2=list(type='rect', line = list(color = 'rgba(0,0,0,0)'), fillcolor="rgba(147,112,219,0.1)", xref='x', yref='y')
shape2_offset = 0.5

shapes2 <- list()


for (i in seq_along(x_start)){
  print(i)
  shape2[["x0"]] <- x_start[i] + shape2_offset
  shape2[["x1"]] <- x_stops[i] + shape2_offset
  shape2[["y0"]] <- 0
  shape2[["y1"]] <- max(df$y2)
  shapes2 <- c(shapes2, list(shape2))
  #print()
}

p1 <- layout(p1, shapes=shapes, xaxis = list(showgrid=FALSE))                 
p2 <- layout(p2, shapes=shapes2)                 


p <- subplot(p1, p2, nrows = 2, margin=0.05)

p

推荐阅读