[英]How could I combine bar char and line graph using Plotly in R?
I have two data.frame
as follows:我有两个
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))
)
And和
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))
)
I want to combine the bar chart create based of df1
and line graph created based on df2
ie I want to combine two plotly (fig1 and fig2) in one.我想结合基于
df1
创建的条形图和基于df2
创建的折线图,即我想将两个绘图(fig1 和 fig2)合二为一。 Like the first figure of link .就像链接的第一个图。
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)
Thanks in advance.提前致谢。
I would suggest next approach using add_trace()
with your second dataframe:我建议使用
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)
Output:输出:
You can further customize the plot in the layout()
option.您可以在
layout()
选项中进一步自定义绘图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.