library(dplyr)
library(ggplot2)

# 生成示例数据
set.seed(123)
df1 <- data.frame(
  Gas = rep(c("CH4", "CO2"), each = 100),
  Date = seq(as.Date("2021-01-01"), by = "day", length.out = 100),
  Flux = runif(200, min = 0, max = 100),
  Hybrid = rep(c("A", "B"), each = 50, times = 2),
  Nrate = runif(200, min = 0, max = 10)
)
df2 <- data.frame(
  Gas = rep(c("CH4", "CO2"), each = 10),
  Date = seq(as.Date("2021-01-01"), by = "day", length.out = 10),
  Flux = runif(20, min = 0, max = 100),
  Hybrid = rep(c("A", "B"), each = 5, times = 2),
  Nrate = runif(20, min = 0, max = 10)
)

# 大折线图
df1 %>%
  ggplot(aes(x = Date, y = Flux, color = Hybrid)) +
  geom_line() +
  facet_grid(Gas ~ ., scales = "free_y") +
  theme_bw() +
  theme(legend.position = "none") +
  labs(x = "Date", y = "Flux")

# 小折线图
df2 %>%
  ggplot(aes(x = Date, y = Flux, color = Hybrid)) +
  geom_line() +
  theme_bw() +
  theme(legend.position = "none") +
  coord_cartesian(xlim = c(as.Date("2021-01-10"), as.Date("2021-01-20")),
                  ylim = c(0, 100),
                  clip = "off") +
  annotation_custom(
    ggplotGrob(
      ggplot(df1, aes(x = Date, y = Flux, color = Hybrid)) +
        geom_line() +
        facet_grid(Gas ~ ., scales = "free_y") +
        theme_bw() +
        theme(panel.background = element_blank(),
              axis.line = element_blank(),
              axis.text.x = element_blank(),
              axis.ticks.x = element_blank(),
              axis.title.x = element_blank(),
              axis.title.y = element_blank(),
              plot.margin = unit(c(-1, -1, -1, -1), "cm")) +
        coord_cartesian(xlim = c(as.Date("2021-01-10"), as.Date("2021-01-20")),
                        ylim = c(0, 100),
                        clip = "off")
    ),
    xmin = as.numeric(as.Date("2021-01-15")),
    xmax = Inf,
    ymin = as.numeric(quantile(df1$Flux, 0.95)),
    ymax = Inf
  )
有两个数据框df1和df2均含有Gas、Date、Flux、Hybrid和Nrate等指标两个数据框的行数差距很大现利用dplyr和ggplot做df1以Date为横坐标Flux为纵坐标Hybrid和Gas为分面颜色为Hybrid的折线图在每个分面图右上角四分之一的面积添加一个小折线图小折线图使用df2的数据且映射和大折线图相同

原文地址: http://www.cveoy.top/t/topic/6iV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录