r 将多个ggplot2图与一个共同的x轴和不同的y轴对齐,每个轴都有不同的y轴标签。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r 将多个ggplot2图与一个共同的x轴和不同的y轴对齐,每个轴都有不同的y轴标签。相关的知识,希望对你有一定的参考价值。

#' When plotting multiple data series that share a common x axis but different y axes,
#' we can just plot each graph separately. This suffers from the drawback that the shared axis will typically
#' not align across graphs due to different plot margins.
#' One easy solution is to reshape2::melt() the data and use ggplot2's facet_grid() mapping. However, there is
#' no way to label individual y axes.
#' facet_grid() and facet_wrap() were designed to plot small multiples, where both x- and y-axis ranges are
#' shared acros all plots in the facetting. While the facet_ calls allow us to use different scales with
#' the \code{scales = "free"} argument, they should not be used this way.
#' A more robust approach is to the grid package grid.draw(), rbind() and ggplotGrob() to create a grid of 
#' individual plots where the plot axes are properly aligned within the grid.
#' Thanks to https://rpubs.com/MarkusLoew/13295 for the grid.arrange() idea.

library(ggplot2)
library(grid)
library(dplyr)

#' Create some data to play with. Two time series with the same timestamp.
df <- data.frame(DateTime = ymd("2010-07-01") + c(0:8760) * hours(2), series1 = rnorm(8761), series2 = rnorm(8761, 100))

#' Create the two plots.
plot1 <- df %>%
  select(DateTime, series1) %>%
  na.omit() %>%
  ggplot() +
  geom_point(aes(x = DateTime, y = series1), size = 0.5, alpha = 0.75) +
  ylab("Red dots / m") +
  theme_minimal() +
  theme(axis.title.x = element_blank())

plot2 <- df %>%
  select(DateTime, series2) %>%
  na.omit() %>%
  ggplot() +
  geom_point(aes(x = DateTime, y = series2), size = 0.5, alpha = 0.75) +
  ylab("Blue drops / L") +
  theme_minimal() +
  theme(axis.title.x = element_blank())

grid.newpage()
grid.draw(rbind(ggplotGrob(plot1), ggplotGrob(plot2), size = "last"))

以上是关于r 将多个ggplot2图与一个共同的x轴和不同的y轴对齐,每个轴都有不同的y轴标签。的主要内容,如果未能解决你的问题,请参考以下文章

R语言可视化包ggplot2包设置轴断点位置实战(Axis Breaks)即自定义X轴和Y轴的数值标记位置

ggplot2 - 在大小图例中显示多个键(形状)

R语言ggplot2可视化:默认情况下ggplot2在x轴和y轴的刻度线和轴之间保留了一些空间设置ggplot2可视化去除可视化结果与坐标轴之间的空间可视化结果与坐标轴紧紧贴合,没有空白区域

R语言ggplot2可视化:ggplot2中使用element_text函数设置轴标签文本粗体字体(bold text,使x轴和Y轴的标签文本都使用粗体字体)注意是轴标签而非轴标题

R语言ggplot2可视化时间序列散点图X轴和Y轴都是时间信息使用labels参数在scale_y_datetime函数中自定义指定Y轴时间信息轴标签刻度显示的格式

我有 2 个不同的条形图,它们有一个共同的 X 轴和 2 个不同的 Y 轴。我想使用 python 将这两个使用 X 轴的图合并为一个