1

I am trying to plot multiple histograms in one plot with R. I did the plot with 'plot' and 'line' in a loop but I would like to do my plot with ggplot and use the function geom_step().

Here, my code:

png(file = "MismatchAll_300_test.png", width = 1500, height = 1000,  pointsize = 30)

# Calcul correction
##########################################################


for (i in 1:length(fileNames1)) {


 TablS1 <- as.data.frame(DataS1[i], col.names = "") #DataS1 is a vector of 300 datasets

 Hist <- hist(TablS1$modif1, breaks = seq(-0.025, 0.25, by=0.003), plot=F)

 mismatch1 <- data.frame(Hist$counts)
 mismatch1 <- transform(mismatch1, NbDiff = Hist$mids)
 mismatch1 <- transform(mismatch1, FreqS = round(prop.table(Hist.counts)*100, digits = 3))
 mismatch1 <- mismatch1[,-1]

 #Plot with "plot"

 if (i==1) {
   plot(mismatch1, type="l", ylim=c(0,15), col="grey", main=expression('TCMD for '*italic(Epi)*' = 10, '*italic(m)*' = 0.0024 and '*italic(Kmax)*' = 250'),
        xlab = "Time corrected pairwise differences (d̆)", ylab = "Frequency (%)")

 }

 lines(mismatch1, col="grey")


 # Plot with ggplot

 if (i==1){
 p <- ggplot(mismatch1, aes(NbDiff, y = value, color = Legend)) + 
   geom_step(aes(y = FreqS, col = "Simulation"), size=1) +
   labs(y="Frequency (%)", x="Differences") +
   #geom_vline(aes(xintercept=piS1, col="Simulation"), size=1) + 
   #geom_vline(aes(xintercept=piD, col="Data"), size=1) +
   theme(legend.position = "right", legend.key.size = unit(2, "line"), 
         legend.text = element_text(size=25, face="bold"), legend.title = element_blank(),
         axis.title.x = element_text(face="bold", size=25, vjust = -0.5), axis.text.x  = element_text(size=25), 
         axis.title.y = element_text(face="bold", size=25, vjust = 0.5), axis.text.y  = element_text(size=25))
 print(p)
 }

g <- p + geom_step(aes(x= mismatch1$NbDiff, y = mismatch1$FreqS, col = "Simulation"), size=1)

 print(g)


}

lines(DataD, col="red", lwd=2)
lines(DataS, col="black", lwd=2)
dev.off()

Here the picture that I got with 'plot'.

enter image description here

However, I can't do the same plot with ggplot. Could someone help me to do a similar figure with ggplot in a loop?

Thank you for your help.

Logica
  • 977
  • 4
  • 16
Myli
  • 21
  • 4
  • Hi. Please read this post and kindly modify your question accordingly. Makes it much more likely that someone will help you. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – tjebo Mar 23 '20 at 11:49

0 Answers0