首页 > 解决方案 > 使用 ggplot2 在轴的特定点添加自定义文本

问题描述

我已经创建了下面的图,我想在下面的示例图片中x-axis这两条垂直线相交的点中添加自定义文本。x-axis第一个βi和第二个βj。这怎么可能?

在此处输入图像描述

# 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)) +
  lims(x = c(-6, 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")

标签: rggplot2

解决方案


这可能很有用。由于我不清楚我使用@AllanCameron解决方案来提示标签的放置(非常感谢):

library(ggplot2)
#Code
ggplot(df, aes(theta, P_item_rasch)) +
  geom_line(aes(color = number)) +
  #lims(x = c(-6, 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")+
  scale_x_continuous(breaks = c(-6,-3,-1,0,1,3,6),limits = c(-6,6),
                     labels=c(-6,-3,expression(beta[i]),0,
                              expression(beta[j]),
                              3,6))+
  xlab(expression(theta))

输出:

在此处输入图像描述


推荐阅读