library(ggpubr)set.seed(1234)wdata=data.frame( sex =factor(rep(c("F", "M"), each=200)), weight =c(rnorm(200, 55), rnorm(200, 58)))head(wdata)#> sex weight#> 1 F 53.79293#> 2 F 55.27743#> 3 F 56.08444#> 4 F 52.65430#> 5 F 55.42912#> 6 F 55.50606gghistogram(wdata, x ="weight", add ="mean", rug =TRUE, fill ="sex", palette =c("#00AFBB", "#E7B800"))#> Warning: Using `bins = 30` by default. Pick better value with the argument#> `bins`.
Code
# 1. Create the histogram plotphist<-gghistogram(wdata, x ="weight", add ="mean", rug =TRUE, fill ="sex", palette =c("#00AFBB", "#E7B800"))#> Warning: Using `bins = 30` by default. Pick better value with the argument#> `bins`.# 2. Create the density plot with y-axis on the right# Remove x axis elementspdensity<-ggdensity(wdata, x ="weight", color="sex", palette =c("#00AFBB", "#E7B800"), alpha =0)+scale_y_continuous(expand =expansion(mult =c(0, 0.05)), position ="right")+theme_half_open(11, rel_small =1)+rremove("x.axis")+rremove("xlab")+rremove("x.text")+rremove("x.ticks")+rremove("legend")# 3. Align the two plots and then overlay them.aligned_plots<-cowplot::align_plots(phist, pdensity, align="hv", axis="tblr")ggdraw(aligned_plots[[1]])+draw_plot(aligned_plots[[2]])
# manually align and plot on top of each otheraligned_plots<-cowplot::align_plots(p1, p2, align="hv", axis="tblr")# Note: In most cases two y-axes should not be used, but this example# illustrates how one could accomplish it.ggdraw(aligned_plots[[1]])+draw_plot(aligned_plots[[2]])