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

如何在ggplot2条形图中设置Y轴仅显示-1、0、1无小数标签

解决ggplot2+patchwork分组条形图Y轴刻度问题

需求说明

  • 所有子图的Y轴仅显示-1、0、1三个刻度标签
  • 移除刻度标签的小数部分(如将-1.0改为-1)

优化后的代码

# 定义统一的Y轴设置规则,避免重复编写代码
custom_y_scale <- scale_y_continuous(
  breaks = c(-1, 0, 1),  # 强制显示指定的三个刻度值
  labels = as.integer,    # 将刻度值转为整数格式,自动去掉小数后缀
  guide = guide_axis(check.overlap = TRUE)
)

Nmx_c1_plot <- ggplot(dataNmxc1,aes(x=Parameter,y=Val, fill = Pathway)) + 
  geom_bar(stat='identity',position = position_dodge()) +
  coord_flip()+
  custom_y_scale

Hpx_c1_plot <- ggplot(dataHpxc1,aes(x=Parameter,y=Val, fill = Pathway)) + 
  geom_bar(stat='identity',position = position_dodge()) +
  coord_flip()+
  custom_y_scale

Nmx_c2_plot <- ggplot(dataNmxc2,aes(x=Parameter,y=Val, fill = Pathway)) + 
  geom_bar(stat='identity',position = position_dodge()) +
  coord_flip()+
  custom_y_scale

Hpx_c2_plot <- ggplot(dataHpxc2,aes(x=Parameter,y=Val, fill = Pathway)) + 
  geom_bar(stat='identity',position = position_dodge())+ 
  coord_flip()+
  custom_y_scale

patchwork <- Nmx_c1_plot + Nmx_c2_plot + Hpx_c1_plot + Hpx_c2_plot 
SensFig <- patchwork + plot_annotation(tag_levels = list(c("(A)","(B)","(C)","(D)"))) 

关键修改说明

  1. 固定刻度值:替换原代码中自动生成刻度的pretty_breaks(),直接指定breaks = c(-1, 0, 1),确保Y轴只显示需求中的三个刻度,解决刻度重叠问题。
  2. 格式化标签:通过labels = as.integer将数值型刻度转为整数格式,自动去除.0这类多余小数;也可以手动指定labels = c("-1", "0", "1"),效果一致。
  3. 代码复用:定义custom_y_scale统一管理Y轴样式,避免重复编写相同的scale配置,提升代码可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:16:02