You need to enable JavaScript to run this app. R语言ggplot2如何在x轴指定交点添加βi、βj自定义文本
优惠活动
大模型
产品
解决方案
定价
更多

R语言ggplot2如何在x轴指定交点添加βi、βj自定义文本

实现方案

你需要在垂直虚线对应的x坐标(B_j=-1对应βj、B_i=1对应βi)位置添加自定义轴标注,两种常用实现方式如下:

方法1:自定义x轴刻度(推荐,风格统一)

直接将两个难度参数加入x轴刻度列表,替换默认刻度文本,无需额外调整绘图区域:

  • 修改原有代码里的lims(x = c(-6, 6))行,替换为以下代码:
scale_x_continuous(
  # 自定义刻度位置,常规刻度值可按需调整
  breaks = c(-6, -4, -2, -1, 0, 1, 2, 4, 6),
  # 对应刻度的文本,用expression渲染斜体+下标格式
  labels = c("-6", "-4", "-2", expression(beta[j]), "0", expression(beta[i]), "2", "4", "6")
)

方法2:轴下方手动添加注释文本

如果不想改动原有x轴的默认刻度,只在轴下方额外添加标注,可使用annotate实现,需临时留出轴下空间避免文本被裁剪:

  • 在原有theme(legend.position = "none")行之前添加以下代码:
# 关闭绘图区域裁剪,允许文本显示在轴外
coord_cartesian(clip = "off") +
# 在指定x位置添加文本,y设为略低于x轴基线的位置
annotate(
  "text",
  x = c(-1, 1),
  y = -0.03, # 可按需调整数值控制文本离轴的距离
  label = c("beta[j]", "beta[i]"),
  parse = TRUE, # 开启数学表达式解析,渲染下标格式
  vjust = 1
)

完整可运行代码参考(以方法1为例)

# Set x-axis values
theta <- seq(from = -10, to = 10, by = 0.001)

B_i <- 1
B_j <- -1
P_item0_rasch <- NULL
P_item1_rasch <- NULL
P_item2_rasch <- NULL
for (i in 1:length(theta)){
  P_item0_rasch[i] <- (exp((theta[i])))/(1+(exp((theta[i]))))
  P_item1_rasch[i] <- (exp((theta[i]-B_i)))/(1+(exp((theta[i]-B_i))))
  P_item2_rasch[i] <- (exp((theta[i]-B_j)))/(1+(exp((theta[i]-B_j))))
}

df <- data.frame(theta = rep(theta, 3),
                 P_item_rasch = c(P_item0_rasch, P_item1_rasch, P_item2_rasch),
                 number = factor(rep(1:3, each = length(theta))))

library(ggplot2)

ggplot(df, aes(theta, P_item_rasch)) +
  geom_line(aes(color = number)) +
  # 替换原有x轴lims的自定义刻度代码
  scale_x_continuous(
    breaks = c(-6, -4, -2, -1, 0, 1, 2, 4, 6),
    labels = c("-6", "-4", "-2", expression(beta[j]), "0", expression(beta[i]), "2", "4", "6")
  ) +
  # Line between curves
  geom_segment(x = -1, xend = 1, y = 0.5, yend = 0.5, lty = 2) +
  # Optional line on left
  geom_segment(x = -Inf, xend = -1, y = 0.5, yend = 0.5, lty = 2) +
  # Lower lines
  geom_segment(data = data.frame(theta = c(-1, 0, 1), P_item_rasch = rep(-Inf, 3)),
               aes(xend = theta, yend = 0.5), lty = 2) +
  # Upper lines
  #geom_segment(data = data.frame(theta = c(-1, 0, 1), P_item_rasch = rep(Inf, 3)),
  #            aes(xend = theta, yend = 0.5), lty = 2) +
  scale_color_manual(values = RColorBrewer::brewer.pal(4, "Set1")[-1]) +
  theme_classic() +
  theme(legend.position = "none")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 11:06:00