r - 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
推荐阅读
- asp.net - .NET 通过 Microsoft Jet 引擎访问受感染的 Excel 文件(带有勒索软件),这会影响或感染服务器吗?
- javascript - Bcrypt.compare 不在 chai/mocha 测试中执行,而是在代码中执行
- javascript - ajax发布后重定向到url不起作用
- java - 如何将svg中的前景色更改为png转换?
- javascript - 选择输入单选时更改最近类的样式 - Javascript
- java - 查找具有不同值的 CSS 选择器的问题
- php - 最大文件大小的 Laravel 验证规则不起作用
- scala - Scala中使用jdk10的不确定数组复制
- c# - 标签不填充
- django - 会话的 Django 设置是什么?