this is part of my code, I wanted a clean solution to put all my plots in one pdf file.
I loop over the case of a density plot and a count plot (frequency). Then I plot a lot of different axis possibilities each for 8 different bin numbers of the histograms. I put a little fragment of my code for the case of log lin. After I saved all the plots for different bin numbers for a case in a list, I recall them and save them together in a pdf. However the problem appears that when I do them separately everything is fine, but when I recall them, my geom_vline does not match the tops of my histogram anymore, so it does not fit well.
Can anybody explain why this happens? And how I can fix this? At this moment the only solution I can think of is just plot it separately for every bin number, but then I end op with a lot of different pdf files which is not very practical.
# log x lin y
someplot <- ggplot(df_test, aes(data_to_test)) +
ggtitle(titletext_histogram) +
scale_x_log10(limits = c(plotxmin_log, plotxmax_log), breaks = scales::trans_breaks("log10", function(x) 10^x),labels = scales::trans_format("log10", scales::math_format(10^.x))) +
annotation_logticks(sides = "b")
if (density)
{ # Density histograms in R normalise to the plot range; we want to normalise to ]0, infinity[, so a correction factor is needed.
someplot <- someplot + geom_histogram(bins = num_bins, aes(y = ..density.. * (cdf(plotxmax_log) - cdf(plotxmin_log))))
} else
{ # Count histogram
someplot <- someplot + geom_histogram(bins = num_bins, aes(y=..count..))
}
someplot <- someplot + stat_function(fun = powerlaw_logpdf , color = "red") +
stat_function(fun = lognormal_logpdf, color = "green3")
labs(x=xtext_histogram, y=ytext_histogram) +
theme_grey(base_size = 15) +
theme(plot.title = element_text(hjust = 0.5)) +
geom_vline(xintercept=lognormal$xmin,linetype="dashed", color = "green3") +
geom_vline(xintercept=powerlaw$xmin,linetype="dashed", color = "red")
loglin[[i]]= someplot
}
pdf(file.path('.', subdir_name, 'histograms',filename_histogram_log_lin), width=9, height=6, onefile = TRUE)
print(loglin)
while (!is.null(dev.list())) dev.off()
}}