利用ggpubr绘制双坐标轴

简介: 之前画双Y轴的图都是自己写函数用ggplot2去制作,偶然间发现了ggpubr包一种可视化的形式,大家可以一起学习下~

之前画双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
)

e9333b4d20d41c9b3799bf923b34705.png

绘制双 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]])

dab126b98b5443e311779a285f51f88.png

参考链接:https://www.datanovia.com/en/blog/ggplot-histogram-with-density-curve-in-r-using-secondary-y-axis/](https://www.datanovia.com/en/blog/ggplot-histogram-with-density-curve-in-r-using-secondary-y-axis/)

相关实践学习
基于阿里云DeepGPU实例,用AI画唯美国风少女
本实验基于阿里云DeepGPU实例,使用aiacctorch加速stable-diffusion-webui,用AI画唯美国风少女,可提升性能至高至原性能的2.6倍。
相关文章
|
2月前
用贝舍尔曲线绘制分段闭合圆环
用贝舍尔曲线绘制分段闭合圆环
21 0
|
8月前
echarts折线图折线点大小,颜色,折线的颜色设置
echarts折线图折线点大小,颜色,折线的颜色设置
42 1
|
2月前
使用分面展示不同组别的双 Y 轴图形
使用分面展示不同组别的双 Y 轴图形
51 0
|
8月前
Echarts折线图的x和y轴坐标颜色修改
Echarts折线图的x和y轴坐标颜色修改
146 1
|
2月前
Echarts柱状图x轴刻度间隔显示不全/x轴文字倾斜
Echarts柱状图x轴刻度间隔显示不全/x轴文字倾斜
225 0
|
8月前
|
JSON 数据格式
Echarts折线图的折线实线设置成虚线
Echarts折线图的折线实线设置成虚线
127 0
|
8月前
echarts折线图线条颜色和区域颜色设置
echarts折线图线条颜色和区域颜色设置
109 0
|
9月前
42Echarts - 柱状图(坐标轴刻度与标签对齐)
42Echarts - 柱状图(坐标轴刻度与标签对齐)
93 0
|
数据挖掘 Python
【python数据分析】绘制双Y轴坐标系
前言 Matplotlib绘制出的图形中会存在一些问题,例如:如何绘制双Y轴坐标系?如何去掉图形默认的边框?以及如何移动坐标到指定位置?下面我们就来看看如何解决
【python数据分析】绘制双Y轴坐标系
|
11月前
echarts 图表解决Y轴刻度在某些情况下不为整数问题
echarts 图表解决Y轴刻度在某些情况下不为整数问题
276 0