[英]How could I plot a continuous line in bar- line Plotly object in R?
[英]How could I combine bar char and line graph using Plotly in R?
我有兩個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))
)
我想結合基於df1
創建的條形圖和基於df2
創建的折線圖,即我想將兩個繪圖(fig1 和 fig2)合二為一。 就像鏈接的第一個圖。
fig1 <- df1 %>%
plotly::plot_ly(x = ~week, y = ~count, type = "bar", split = ~cat)
fig2 <- df2 %>%
plotly::plot_ly(x = ~week, y = ~count, type = "scatter", mode = "lines", split = ~cat)
提前致謝。
我建議使用add_trace()
和第二個數據幀的下一種方法:
library(plotly)
#Data
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))
)
#Plot
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)
輸出:
您可以在layout()
選項中進一步自定義繪圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.