我正在通过dput和注释的data.table
封闭示例数据集,以询问有关使用geom_text进行文本水平移位的问题。
library("data.table")
library("ggplot2")
# prevs2
dput(prevs2)
prevs2 <- structure(list(V1 = c("XY02", "XY03", "XY04", "XY16", "XY17"),
V2 = c(1L, 15L, 4L, 1L, 1L), N = c(66L, 130L, 55L, 3L, 17L
), Prevalence = c(0.0151515151515152, 0.115384615384615,
0.0727272727272727, 0.333333333333333, 0.0588235294117647
), LCL = c(0.00180338800237566, 0.0804738966923874, 0.0443506970334619,
0.28182217271425, 0.0331125475431457), UCL = c(0.0284996423006546,
0.150295334076843, 0.101103848421084, 0.384844493952417,
0.0845345112803837)), class = c("data.table", "data.frame"
), row.names = c(NA, -5L), .internal.selfref = <pointer: 0x003e2498>)
prevs2在下面显示为data.table
:
# V1 V2 N Prevalence LCL UCL
# 1: XY02 1 66 0.01515152 0.001803388 0.02849964
# 2: XY03 15 130 0.11538462 0.080473897 0.15029533
# 3: XY04 4 55 0.07272727 0.044350697 0.10110385
# 4: XY16 1 3 0.33333333 0.281822173 0.38484449
# 5: XY17 1 17 0.05882353 0.033112548 0.08453451
以下ggplot2
代码产生下图。
ggplot(prevs2, aes(x = reorder(V1, -Prevalence), y = Prevalence)) +
geom_col() + geom_errorbar(aes(ymin = LCL, ymax = UCL), width = 0.1) +
xlab("V1") + ylab("Prevalence") + geom_point(aes(y = Prevalence)) +
theme(axis.text.x = element_text(size = rel(1.5), angle = 90),
panel.background = element_rect(fill = "white", colour = "grey50")) +
theme(plot.margin = unit(c(2, 2, 2, 2), "pt")) + geom_text(aes(label =
N), position = position_dodge(width = 0.9), vjust = -0.9, hjust = -0.9)+
theme(text = element_text(size = 12, family = "sans"))
对于图中的5个geom_cols中的每一个,是否有必要修改上面的ggplot2
代码以使其与误差线的水平位移相等?
如果不是,是因为水平距离由文本的长度决定(例如130比其他值靠右)?
答案 0 :(得分:1)
您可以使用hjust = "left"
,使文本的左边缘与错误栏对齐。然后nudge_x
将其移开一点:
ggplot(prevs2, aes(x = reorder(V1, -Prevalence), y = Prevalence)) +
geom_col() + geom_errorbar(aes(ymin = LCL, ymax = UCL), width = 0.1) +
xlab("V1") + ylab("Prevalence") + geom_point(aes(y = Prevalence)) +
theme(axis.text.x = element_text(size = rel(1.5), angle = 90),
panel.background = element_rect(fill = "white", colour = "grey50")) +
theme(plot.margin = unit(c(2, 2, 2, 2), "pt")) +
geom_text(aes(label = N),
vjust = -0.9, hjust = "left", nudge_x = 0.1)+
theme(text = element_text(size = 12, family = "sans"))
我删除了position_dodge
,因为我不认为它实际上在做什么,每个x值只有一个小节。
结果: