ggplot2绘制渐变布局云雨图

2023-09-11 08:48:38 浏览数 (2)

❝本节来介绍如何使用「ggplot2」来绘制渐变图形,下面小编使用palmerpenguins包内置的企鹅数据集来进行展示仅作图形展示用,希望各位观众老爷能够喜欢。❞

加载R包

代码语言:javascript复制
library(tidyverse)
library(ggdist)
library(palmerpenguins)
library(gghalves)

数据清洗

代码语言:javascript复制
plot_data <- penguins %>%
  select(species, body_mass_g) %>%
  drop_na()

数据可视化

代码语言:javascript复制
ggplot(data = plot_data, mapping = aes(x = species, y = body_mass_g, fill = species))  
  # 添加渐变区间,位置设置为"dodge"以避免重叠,不显示边框色
  stat_gradientinterval(position = "dodge",colour = NA, width = 0.8)  
  # 添加半眼图形,调整各种视觉参数
  stat_halfeye(adjust = .3,width = .3,.width = 0,
               justification = -.3,point_colour = 'NA',
               slab_fill=NA, slab_colour='#3e2c12',
               slab_size=0.4)  
  # 添加箱型图,设置宽度和异常值形状
  geom_boxplot(width = .15,outlier.shape = NA,fill='#fafafa')  
  # 添加半点图,设置透明度和大小
  geom_half_point(side  = "l",alpha = 0.1, size  = 1.8)  
  # 设置坐标轴范围和裁剪方式
  coord_cartesian(xlim = c(1, NA),ylim = c(2000, 7000),clip = "off")  
  # 移除图例和透明度指引
  guides(fill="none", alpha='none')  
  labs(x =NULL, y = NULL)     # 移除x和y轴标签  # 应用经典主题
  theme_classic()  
  # 自定义主题设置,例如轴标题、文本、背景等
  theme(axis.title.y =element_blank(),
        axis.text = element_text(hjust = 0.5,size=10,color = "black"),
        plot.background = element_rect(fill = "#fafafa", colour="#fafafa"),
        panel.background = element_rect(fill = "#fafafa", colour="#fafafa"),
        plot.margin = unit(c(0.3,0.3,0.3,0.3), "cm"),
        legend.position = "none",
        axis.ticks = element_blank())

0 人点赞