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

如何缩小绘图X轴上两个分类变量间的空白区域

解决分类变量X轴大量空白的问题

你的问题出在强行将离散分类变量转为连续轴处理,反而导致X轴范围未被正确限定。以下是两种可行的解决方案:

方案1:保留离散轴属性(推荐)

如果pers_whobreaks是数值型变量,先将其转换为因子,确保plot_model识别为分类轴:

# 先将自变量转为因子(根据你的实际编码调整levels)
persconf_mean_mod1.2$data$pers_whobreaks <- factor(
  persconf_mean_mod1.2$data$pers_whobreaks,
  levels = c(0, 1),  # 替换为你数据中实际的数值编码
  labels = c("Partner Breaksup", "You Breakup")
)

# 重新绘图
plot_model(persconf_mean_mod1.2, 
           type = "pred", 
           terms = c("pers_whobreaks", 
                     "avd_mc[-1.114652, 1.114652]")) + 
  scale_color_discrete(name = "Attachment Avoidance", 
                       labels = c("Low", "High"))+ 
  scale_x_discrete(expand = c(0.1, 0.1)) +  # 缩小轴两端空白
  ggtitle("")+ 
  ylab("Personal Confidence") + 
  xlab("Initiator")+ 
  theme_classic() + 
  theme(text = element_text(family = "serif"))

expand参数可以直接控制离散轴两端的空白大小,数值越小空白越少。

方案2:限定连续轴显示范围

如果不想转换变量类型,用coord_cartesian()强制裁剪X轴显示范围,去掉多余空白:

plot_model(persconf_mean_mod1.2, 
           type = "pred", 
           terms = c("pers_whobreaks", 
                     "avd_mc[-1.114652, 1.114652]")) + 
  scale_color_discrete(name = "Attachment Avoidance", 
                       labels = c("Low", "High"))+ 
  scale_x_continuous(labels = c("Partner Breaksup" , "You Breakup"), 
                     breaks = c(0, 1)) +  # 替换为你数据中实际的数值编码
  ggtitle("")+ 
  ylab("Personal Confidence") + 
  xlab("Initiator")+ 
  theme_classic() + 
  theme(text = element_text(family = "serif")) +
  coord_cartesian(xlim = c(-0.2, 1.2))  # 仅显示0-1附近区域,去掉左右空白

这里的xlim需要根据你数据中pers_whobreaks的实际数值调整,比如如果是1和2,就设为c(0.8, 2.2),确保两个类别标签都能完整显示,同时去掉多余空白。

内容的提问来源于stack exchange,提问作者captain broccoli heart

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 02:42:28