Home > Mobile >  how to merge two seperate histograms into one
how to merge two seperate histograms into one

Time:05-13

I have the following code:

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")

Where QualidadeARO3 is a data sheet imported from Excel that looks like this:

enter image description here

And

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") 

gives the following ouput: enter image description here

and

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")

gives: enter image description here

This is good and all so far, but my problem is that both graphs "run" independently, i.e., when I call the second ggplot the first graph disappears, when I want to overlap both into a single histogram, as well as both color labels. I have seen Overlaying histograms with ggplot2 in R , but still no clue. Any help?

CodePudding user response:

Try having separate geom layers like this:

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") 

You can also use scale_fill_manual instead of scale_color_discrete if you want to have specific colors.

  • Related