You need to enable JavaScript to run this app. R ggridges包绘制山脊图时Y轴刻度及标签无法显示问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

R ggridges包绘制山脊图时Y轴刻度及标签无法显示问题咨询

问题原因

  • 你的time变量为数值类型,最初的代码错误使用scale_y_discrete()处理连续型Y轴映射,导致刻度无法渲染
  • 修改后代码给scale_y_reverse()的limits参数传入了3个值,该参数仅支持传入长度为2的向量定义坐标轴上下限,参数格式错误直接导致代码运行失败
  • theme_ridges默认隐藏了Y轴的刻度和对应文本,需要额外覆写主题参数开启显示

可行解决代码

首先调整数据格式,再修改绘图代码即可:

# 加载所需包
library(ggplot2)
library(ggridges)

# 样例数据预处理:将time转为因子保证分组正确,gender指定因子顺序匹配颜色映射
order_math<-c(1,2,1,2,3,3,1,2,3,1,2,3)
gender<-factor(c("M","F","M","M","M","F","F","M","F","M","M","F"), levels = c("F", "M"))
time<-factor(c(1,1,2,3,3,2,1,2,3,2,3,1))
sample<-data.frame(order_math,gender,time)

# 绘图代码 可直接替换sample为你的math_dat使用
ggplot(sample, aes(x = order_math, y = time, color = gender, point_color = gender, fill = gender)) +
  geom_density_ridges(
    jittered_points = TRUE, scale = .95, rel_min_height = .01,
    point_shape = "|", point_size = 3, size = 0.25,
    position = position_points_jitter(height = 0)
  ) +
  scale_y_discrete(expand = c(0, 0), name = "Time") + # 对应因子型time的离散刻度
  scale_x_continuous(expand = c(0, 0), name = "Rankings") +
  scale_fill_manual(values = c("#D55E0050", "#0072B250"), labels = c("female", "male")) +
  scale_color_manual(values = c("#D55E00", "#0072B2"), guide = "none") +
  scale_discrete_manual("point_color", values = c("#D55E00", "#0072B2"), guide = "none") +
  coord_cartesian(clip = "off") +
  guides(fill = guide_legend(
    override.aes = list(
      fill = c("#D55E00A0", "#0072B2A0"),
      color = NA, point_color = NA)
  )
  ) +
  ggtitle("Ranks over time") +
  theme_ridges(center = TRUE) +
  # 覆写theme_ridges的默认配置,开启Y轴刻度和文本
  theme(
    axis.ticks.y = element_line(size=0.5, colour = "black"),
    axis.ticks.length = unit(5, "pt"),
    axis.text.y = element_text(vjust = 0.4),
    axis.title.y = element_text()
  )

补充说明

如果你的实际数据中time是连续的年份/数值序列,不需要反向排序就不要加scale_y_reverse(),如果确实需要反向排序,把因子的levels倒转即可,不需要修改scale参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 11:36:04