之前画双Y轴的图都是自己写函数用ggplot2去制作,偶然间发现了ggpubr包一种可视化的形式,大家可以一起学习下~
加载包构建数据
library(ggpubr) library(cowplot) set.seed(1234) wdata = data.frame( sex = factor(rep(c("F", "M"), each=200)), weight = c(rnorm(200, 55), rnorm(200, 58))) head(wdata)
基础直方图
# Basic histogram without the density curve gghistogram( wdata, x = "weight", add = "mean", rug = TRUE, fill = "sex", palette = c("#00AFBB", "#E7B800") ) # Add the density curve on the same axis gghistogram( wdata, x = "weight", y = "..density..", add = "mean", rug = TRUE, fill = "sex", palette = c("#00AFBB", "#E7B800"), add_density = TRUE )
绘制双 Y 轴
原理其实就是先绘制直方图,再绘制密度图,将Y轴放在右侧,X轴的内容删除,合并起来即可
# 1. Create the histogram plot phist <- gghistogram( wdata, x = "weight", add = "mean", rug = TRUE, fill = "sex", palette = c("#00AFBB", "#E7B800") ) # 2. Create the density plot with y-axis on the right # Remove x axis elements pdensity <- 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 <- align_plots(g1,g2, align="hv", axis="tblr") ggdraw(aligned_plots[[1]]) + draw_plot(aligned_plots[[2]])