r - 从两个不同的数据帧绘制 R 图

标签 r ggplot2 r-plotly ggplotly

我正在尝试使用两个不同的 data.frame 绘制折线图在 R 中使用 plotly .问题都是data.frame有不同的维度。data.frame 的样本数据1:

                     DATE   SOC resdiff
 2016  2017-08-11 02:40:00 95.45    0.54
 4033  2017-08-18 02:45:00 94.88    0.56
 6048  2017-08-25 02:45:00 94.28    0.60
 8064  2017-09-01 02:45:00 93.68    0.60
 10080 2017-09-08 02:45:00 92.96    0.72
 12096 2017-09-15 02:45:00 92.13    0.83 
data.frame 的样本数据2:
       data.event_type data.user          data.stamp
 1          config    *INST* 2018-06-27 14:37:29
 2          config    *INST* 2018-02-14 19:30:57
 3          config    *SYNC* 2017-12-18 07:00:53
 4          config    *SYNC* 2017-12-18 06:59:14
 5          config    *INST* 2017-10-03 00:55:25
 6          config    *INST* 2017-09-28 00:49:29
data.frame的折线图1:
library(plotly)
p <- plot_ly(new_res, x = ~DATE) %>%
  add_trace(y = ~resdiff*100, name = 'SOC Diff',type = 'scatter',mode = 
 'lines') %>%
 add_trace(y = ~SOC, name = 'SOC',type = 'scatter', mode = 'lines+markers') 
p
data.frame的折线图2:
p <- plot_ly(get_df[1:9,], x = ~data.stamp) %>%
 add_trace(y = ~data.user, name = 'Event',type = 'scatter',mode = 'markers')
p

现在的问题是如何将这两个折线图合并为一个?是否可以通过添加 add_trace 来实现? ?

请随时建议我使用 ggplot或任何其他图书馆,如果它会更容易。

最佳答案

最后,我从这里得到了解决方案:https://plot.ly/r/graphing-multiple-chart-types/

我合并了两个 data.frame
final_df=merge(new_res,get_df[1:9,c(4,5,8)],all.x = TRUE,all.y = TRUE,by="DATE")
并使用 plotly 绘图:

library(plotly)

p <- plot_ly(final_df) %>%
 add_trace(x = ~DATE, y = ~SOC,name = 'SOC',type = 'scatter',mode = 'lines') %>%
 add_trace(x = ~DATE, y = ~resdiff*100, name = 'SOC Diff',type = 'scatter',mode = 'lines+markers') %>%
 add_trace(x = ~DATE, y = ~data.user, yaxis = 'y2',name = 'Event',type = 'scatter',mode = 'markers') %>% 
 layout(title = 'SOC Data',
     xaxis = list(title = ""),
     yaxis = list(side = 'left', title = 'SOC and SOC Diff', showgrid = FALSE, zeroline = FALSE),
     yaxis2 = list(side = 'right', overlaying = "y", title = 'Event Type', showgrid = FALSE, zeroline = FALSE))

p

enter image description here

关于r - 从两个不同的数据帧绘制 R 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52199017/

相关文章:

响应式(Reactive) Shiny 模块共享数据

R ggplot2在同一类别标签中使用斜体和非斜体

R plotly : Custom hover text does not appear when only one stacked bar

r - 在 ggplot2 中的各个方面注释文本

r - 具有刻面比例和动态 geom_text 位置的 ggplot

将悬停标签重新放置在栏的中间,这样它就不会覆盖标题

R Plotly - 绘制多条回归线

r - 使用`assign()`为列表项赋值

r - 如何将图例高度设置为与绘图区域的高度相同?

javascript - 如何创建自定义 JS 函数以将 plotly 图像复制到 R shiny 中的剪贴板