首页 > 解决方案 > 如何组合2个ggplot图?

问题描述

我成功地完成了这个 2 ggplot 图。

右边图表的点是参考左边曲线点的数据。所以结合这张图真的很棒。

y 轴相同,x 只是时间转换为数值向量。

你知道我该怎么做吗?

两个ggplot

X <- 
structure(list(Varietes = c("Abelastone", "Abelastone", "Abelastone", 
"Abelastone", "Abelastone"), ligne.rep = c(1, 1, 1, 1, 1), 
Pied = c(1, 3, 2, 6, 7), Date.floraison.mâle = c(7.29, 8.01, 8.02, 8.03, 
8.04), Date.floraison.femelle = structure(c(1628553600, 1628640000, 
1629158400, 1629849600, 1629158400), tzone = "UTC", class = c("POSIXct", 
"POSIXt")), ASIi = c(12, 10, 15, 22, 13), Hauteur.des.pieds = c(230, 
226, 228, 240, 233), Hauteur.des.soies = c(123, 116, 118, 124, 
122), Cumulatif.mâle = c(1, 2, 3, 4, 5), date.mâle.graph = c(29, 
32, 33, 34, 35), ASIi.floraisons.mâles = c(41, 42, 48, 56, 48
)), row.names = c(NA, -5L), na.action = structure(c(`6` = 6L, 
`10` = 10L, `20` = 20L, `21` = 21L, `24` = 24L), class = "omit"), 
class = c("tbl_df", "tbl", "data.frame"))

代码:

first<- ggplot( X, aes(x=date.mâle.graph, y=Cumulatif.mâle))+ geom_point()+ geom_line(size=1)+ggtitle("Floraison mâle en fonction du temps et de leurs ASIi") + xlab("Floraison mâle") + ylab("Individus de la variété")+ theme_minimal()+theme(
  plot.title = element_text(color="black", size=14, face="plain"),
  axis.title.x = element_text(color="black", size=16, face="plain"),
  axis.title.y = element_text(color="black", size=16, face="plain"),
  axis.text.x = element_text(face="bold", color="#993333", size=14, angle=0),
  axis.text.y = element_text(face="bold", color="#993333", size=14, angle=0))


second<- ggplot( X, aes(x=ASIi.floraisons.mâles, y=Cumulatif.mâle))+ geom_point(shape=20, color="blue", size=4 )+ theme_minimal()


plot_grid(first, second)

标签: rggplot2

解决方案


这类问题通常是数据重组问题。请参阅将 data.frame 从宽格式重塑为长格式
首先,重新格式化XX2,然后绘制点,然后绘制对数据进行子集化的线。
另请注意theme,如果两者axis.title.xaxis.title.y都设置为相同的值,则仅设置更通用的axis.title。对于axis.text.

library(dplyr)
library(tidyr)
library(ggplot2)

X %>%
  select(date.mâle.graph, ASIi.floraisons.mâles, Cumulatif.mâle) %>%
  pivot_longer(
    cols = c(date.mâle.graph, ASIi.floraisons.mâles),
  ) -> X2

ggplot(X2, aes(x = value, y = Cumulatif.mâle, color = name)) +
  geom_point()+
  geom_line(
    data = subset(X2, name == "date.mâle.graph"),
    inherit.aes = TRUE,
    size = 1
  ) +
  ggtitle("Floraison mâle en fonction du temps et de leurs ASIi") +
  xlab("Floraison mâle") +
  ylab("Individus de la variété") +
  xlim(range(pretty(X2$value))) +
  scale_color_manual(values = c("blue", "black")) +
  theme_minimal()+
  theme(
    plot.title = element_text(color="black", size=14, face="plain"),
    axis.title = element_text(color="black", size=16, face="plain"),
    axis.text = element_text(face="bold", color="#993333", size=14, angle=0)#,
  )

推荐阅读