我有两个data.frame
如下:
df1 <- data.frame(
week = c(rep(1, times = 3), rep(2, times = 3)),
cat = rep(c("A", "B", "C"), times = 2),
count = round(runif(6, 1, 10))
)
和
df2 <- data.frame(
week = c(rep(1, times = 2), rep(2, times = 2)),
cat = rep(c("E", "F"), times = 2),
count = round(runif(4, 1, 10))
)
情节代码是
plotly::plot_ly(df1,x = ~week, y = ~count, type = "bar", split = ~cat) %>%
add_trace(data = df2,x = ~week, y = ~count, type = "scatter",
mode = "lines", split = ~cat, yaxis = 'y2') %>%
layout(title = 'Title',
xaxis = list(title = ""),
yaxis = list(side = 'left', title = 'var1', showgrid = FALSE, zeroline = FALSE),
yaxis2 = list(side = 'right', overlaying = "y",
title = 'var2', showgrid = FALSE, zeroline = FALSE),
showlegend = FALSE)
但是我无法为每个组(A、B、C、E 和 F)指定特定的颜色。我试图color = ~cat, colors = c(A = "red", B = "green", C = "yellow")
用于条形图和类似的线图。但不知何故,如果我只使用条形图或线图,它就不起作用了。
谢谢你。
建议在plot_ly
调用中定义颜色,然后使用col = ~cat
参数添加条形和线条。见下文:
plotly::plot_ly(colors = c("A" = "red", "B" = "green", "C" = "yellow", "E" = "blue", "F" = "darkgreen")) %>%
add_bars(data = df1, x = ~week, y = ~count, type = "bar", color = ~cat) %>%
add_trace(data = df2,x = ~week, y = ~count, type = "scatter",
mode = "lines", color = ~cat, yaxis = 'y2') %>%
layout(title = 'Title',
xaxis = list(title = ""),
yaxis = list(side = 'left', title = 'var1', showgrid = FALSE, zeroline = FALSE),
yaxis2 = list(side = 'right', overlaying = "y",
title = 'var2', showgrid = FALSE, zeroline = FALSE),
showlegend = FALSE)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句