r - 使用 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")
解决方案
这可能很有用。由于我不清楚我使用@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))
输出:
推荐阅读
- outlook - Outlook Windows 通知:更改用户体验,使用图标按发件人分组
- php - Laravel 5.8 身份验证在登录后返回登录页面
- r - 反应式文本输出 RShiny - 如何在文本中显示 SQL 查询的输出
- vb.net - GetElementbyID 未显示 IE.Dcoument (VB.Net)
- sql - SQL - 如何识别与表的该列中的正常内容不匹配的表行
- algorithm - 重叠池资源分配算法
- java - 我怎样才能让我的文本文件变成 40x40 矩阵
- python - tkinter 中的马拉雅拉姆语
- asp.net-core - 如何防止预呈现的 Blazor WebAssembly 应用程序中的内容闪烁?
- ios - Swift - 应用内购买完成后 WebView 为零