简体   繁体   English

如何在网格中绘制多个时间序列图,其中每个图都有两个 y 轴?

[英]How to plot multiple time series plots in a grid, where each plot has two y axes?

I need to plot several time series charts on the same page, each in its own panel in a grid 3x2 or similar.我需要在同一页面上绘制多个时间序列图表,每个图表都在 3x2 或类似网格中的自己的面板中。 In the latter case I'd have 6 charts on a page in 3 rows and 2 columns.在后一种情况下,我将在 3 行 2 列的页面上有 6 个图表。 I need to use R, any popular plot library is fine.我需要使用 R,任何流行的绘图库都可以。

Further, each chart will have multiple time series on it.此外,每个图表上都会有多个时间序列。 All but one time series will be scaled to the y-axis on the left hand side, while one time series will be in a different scale with its y labels on the right hand side.除了一个时间序列之外,所有时间序列都将缩放到左侧的 y 轴,而一个时间序列将采用不同的比例,其 y 标签位于右侧。 This is similar to plotyy command in MATLAB.这类似于 MATLAB 中的plotyy命令。

I will need to customize quite a bit, things like colors and line types.我需要自定义很多东西,比如颜色和线条类型。 What's the solution in R for this kind of a chart?对于这种图表,R 中的解决方案是什么?

With ggplot2 we can use facet_wrap to define the facets (panels) and sec_axis to define the secondary axis.使用 ggplot2,我们可以使用facet_wrap来定义面(面板)和sec_axis来定义辅助轴。

library(ggplot2)

ggplot(dd, aes(x, y, col = id)) + 
  geom_line() + 
  facet_wrap(~ panel) +
  scale_y_continuous(sec.axis = sec_axis(~ . / 2))

Note笔记

We used dd defined below as input above.我们使用下面定义的dd作为上面的输入。 id defines the series and panel defines the panel in which each id should be placed. id定义系列, panel 定义每个id应该放置的面板。

set.seed(123)
dd <- data.frame(x = 1:11, y = rnorm(44), 
  id =  gl(4, 11, labels = paste0("ser", 1:4)), 
  panel = gl(2, 22, labels = paste0("panel", 1:2)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM