之前畫雙Y軸的圖都是自己寫函數(shù)用ggplot2去制作银酬,偶然間發(fā)現(xiàn)了ggpubr包一種可視化的形式岭参,大家可以一起學(xué)習(xí)下~
加載包構(gòu)建數(shù)據(jù)
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)
基礎(chǔ)直方圖
# 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
)
圖片.png
繪制雙 Y 軸
原理其實就是先繪制直方圖,再繪制密度圖,將Y軸放在右側(cè),X軸的內(nèi)容刪除,合并起來即可
# 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]])
圖片.png