r-ggplot中轴和数据标签的对齐



我在这里取了一个有趣的ggplot样本,并为我的数据重新制作了它
我的数据是excel文件

`

col <- c("Low weight", "very low weight", "Extra Very Low weight", "Cesarean section", "premature")
> ORpos <- c(6.8, 4.5,0.4, 4.5, 3.9)
> CI1 <- c(0.6, 0.4, 0, 0.2, 0.4)
> CI2 <- c(74, 56, 32, 20, 2.4)
> ORneg <- c(4.8, 15, 6, 6, 4)
> CI3 <- c(0.6, 0.4, 0, 0.2, 0.4)
> CI4 <- c(56, 43, 21, 10, 5)
> md4 <- data.frame(col,ORpos, CI1, CI2, ORneg, CI3, CI4)

plot3 <- ggplot(md4, aes(x = col)) +
geom_col( 
aes(y = Orp, fill = 'Orp')) +geom_text(aes(y=Orp, label = paste(Orp, " [", CI1," ; ", CI2, "]", sep = ""), hjust = -1))+
geom_col( 
aes(y = -Orn, fill = 'Orn')) + geom_text(aes(y=-Orn, label = paste(Orn, " [", CI3," ; ", CI4, "]", sep = ""), hjust = 1))+
coord_flip() +
scale_y_continuous(limits = c(-30, 30))
plot3

但这就是我对R的理解彻底结束的地方
我的绘图

  1. 为什么我的变量在图中的顺序与表中的顺序不同

2对数据标签的处理将在绘图的左右边缘,或者至少正好在彼此下方

对于第一个重新排序问题,您需要通过md4$col = factor(md4$col, levels = unique(md4$col))或仅通过md4$col = factor(md4$col, levels = md4$col)将字符列转换为因子(正如Gregor所指出的(,因为显然您的列中没有重复值。

对于第二个问题,据我所知,对于相对于数据点的左对齐和右对齐文本,hjust应该分别在0到1之间,所以你可能想为你的ORpos数据设置0,为ORneg数据设置1,然后扩展你的刻度以适合所有文本,希望这有帮助:

md4$col = factor(md4$col, levels = rev(md4$col))
ggplot(md4, aes(x = col)) +
geom_col( aes(y = ORpos, fill = 'Positive culter')) +
geom_text(aes(y=7, label = paste(ORpos, " [", CI1,"; ", CI2, "]", sep = " "), hjust = 0))+
geom_col( aes(y = -ORneg, fill = 'Negative culter')) +
geom_text(aes(y=-7, label = paste(ORneg, " [", CI3,"; ", CI4, "]", sep = " "), hjust = 1))+
coord_flip() +
scale_y_continuous(limits = c(-10, 10), breaks = c(-10:10))

最新更新