如何将两个单独的直方图合并为一个

how to merge two seperate histograms into one

我有以下代码:

library("ggplot2") 

x1 = as.numeric(x=QualidadeARO3$Ilhavo)
x2 = as.numeric(x=QualidadeARO3$VNTelha_Maia)

ggplot (QualidadeARO3, aes(x=x1, color="Ílhavo")) +
  geom_histogram(fill="black", position="dodge", alpha = 0.2) +
  theme(legend.position="top") + 
  xlab("microgramas por metro cúbico") + 
  ylab("horas") 

ggplot(QualidadeARO3, aes(x=x2, color="VN Telha-Maia")) +
  geom_histogram(fill="blue", position="dodge", alpha = 0.2)+
  theme(legend.position="top") +
  xlab("microgramas por metro cúbico") + 
  ylab("horas")

其中 QualidadeARO3 是从 Excel 导入的数据 sheet,如下所示:

ggplot (QualidadeARO3, aes(x=x1, color="Ílhavo")) +
  geom_histogram(fill="black", position="dodge", alpha = 0.2) +
  theme(legend.position="top") + 
  xlab("microgramas por metro cúbico") + 
  ylab("horas") 

给出以下输出:

ggplot(QualidadeARO3, aes(x=x2, color="VN Telha-Maia")) +
  geom_histogram(fill="blue", position="dodge", alpha = 0.2)+
  theme(legend.position="top") +
  xlab("microgramas por metro cúbico") + 
  ylab("horas")

给出:

到目前为止一切都很好,但我的问题是两个图都独立地“运行”,即,当我调用第二个 ggplot 时,第一个图消失了,当我想重叠成一个直方图,以及两个颜色标签。 我看过 Overlaying histograms with ggplot2 in R ,但仍然没有头绪。有帮助吗?

尝试像这样使用单独的几何图层:

ggplot (QualidadeARO3) +
  geom_histogram(aes(x=x1, color="Ílhavo", fill="Ílhavo"),
                 position="dodge", alpha = 0.2)+
  geom_histogram(aes(x=x2, color="VN Telha-Maia", fill="VN Telha-Maia"),
                 position="dodge", alpha = 0.2)+
  scale_fill_manual("Type", labels = c("Ílhavo", "VN Telha-Maia"),
                      values= c("black", "blue")) +
  scale_color_discrete("Type", labels = c("Ílhavo", "VN Telha-Maia")) +
  theme(legend.position="top") + 
  xlab("microgramas por metro cúbico") + 
  ylab("horas") 

如果你想要特定的颜色,你也可以使用 scale_fill_manual 而不是 scale_color_discrete