簡體   English   中英

如何在 R 中使用 Plotly 組合條形圖和折線圖?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM