You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改R语言箱线图的X轴分组标签及箱体颜色

解决ggplot箱线图的X轴标签替换与箱体颜色自定义问题

一、替换X轴分组标签

当前X轴显示的1、2、3可通过两种方式替换为对应的文字名称:

方法1:转换因子时直接指定标签

在创建因子列时,通过levels和labels参数映射分组名称:

data$Factor_Rurality <- factor(data$Rurality, 
                               levels = c(1, 2, 3), 
                               labels = c("Urban(城市)", "Suburban(郊区)", "Rural(乡村)"))

方法2:通过scale_x_discrete修改标签

若已创建因子列,可在ggplot中添加该层修改X轴标签:

scale_x_discrete(labels = c("Urban(城市)", "Suburban(郊区)", "Rural(乡村)"))

二、为不同箱体设置自定义颜色

在geom_boxplot的aes中添加fill = Factor_Rurality,再通过scale_fill_manual指定颜色即可,还可统一设置箱体边框颜色。

完整修改后的代码

# 数据准备
Rurality<- c(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
             2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
             2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
             3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0,
             3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0,
             3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0)

CR<- c(895.3, 692.5, 834.6, 571.0, 618.8, 727.9, 286.8, 391.5, 440.9, 442.5, 343.3, 545.3, 205.9, 207.5, 259.7, 495.2,
       689.8, 502.2, 434.9, 325.6, 185.3, 399.4, 218.7, 274.5, 461.4, 367.5, 337.0, 308.5, 334.2, 309.2, 236.6, 278.3,
       349.0, 425.3, 225.7, 369.1, 297.7, 277.7, 425.7, 344.3, 287.5, 190.0, 182.6, 302.8,
       262.8, 290.0, 339.5, 204.0, 333.4, 266.9, 276.4, 210.4, 299.7, 247.1, 237.4, 217.0, 247.4, 234.2, 305.2, 170.0,
       339.5, 237.7, 215.0, 166.4, 283.4, 173.0, 185.1, 217.2, 237.0, 178.6, 280.3, 272.4, 133.8, 245.6, 367.3, 246.3,
       338.5, 187.7, 167.2, 296.4, 262.4, 259.3, 153.6, 189.7, 241.9, 88.7, 153.8, 175.8)

data = data.frame(Rurality, CR)

# 转换因子并指定分组标签
data$Factor_Rurality <- factor(data$Rurality, 
                               levels = c(1, 2, 3), 
                               labels = c("Urban(城市)", "Suburban(郊区)", "Rural(乡村)"))

# 绘制箱线图,自定义颜色和标签
ggplot(data = data, aes(y = CR, x = Factor_Rurality))+
  geom_boxplot(aes(fill = Factor_Rurality), width = 0.65, color = "black")+ # 设置填充色与统一边框色
  stat_boxplot(geom = "errorbar", width = 0.2)+
  geom_point()+
  labs(y = "Chlamydia Rate",
       title = "Chlamydia Rate in Urban, Suburban, and Rural Ohio Counties",
       x= "County Types",
       fill = "County Types")+ # 修改图例标题
  scale_fill_manual(values = c("#FF6B6B", "#4ECDC4", "#45B7D1"))+ # 自定义箱体颜色
  theme(plot.title = element_text(hjust = 0.5, face = "bold")) # 合并主题设置

代码说明

  • 转换因子时指定labels,直接让X轴显示对应分组名称,无需后续修改。
  • aes(fill = Factor_Rurality)实现分组填充色区分,scale_fill_manual支持十六进制颜色码或内置颜色名称自定义颜色。
  • 合并重复的theme设置,简化代码结构。

内容的提问来源于stack exchange,提问作者Brian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:09:57