gpt4 book ai didi

r - ggplot : bar positions shifted right with geom_segment

转载 作者:行者123 更新时间:2023-12-04 09:28:10 25 4
gpt4 key购买 nike

我想在条形图中添加一条短水平线。线的左边缘从 y 轴开始,右边缘延伸到绘图表面。这条线表示 y 轴变量的平均值。我正在使用 geom_segment()添加线条,但这会将条形图的位置向右移动。
如何在不移动条形位置的情况下添加线条?

另外,为什么会发生这种情况?几乎就像 geom_segment()占据渲染表面的一定区域,而不是打印在现有图形的顶部。

示例数据框:

df
x y
1 FALSE 13.02041
2 TRUE 14.37956

geom_segment() :
p <- ggplot(df, aes(x=x, y=y))
p + geom_bar(stat = "identity")

without line

geom_segment() :
avg.y <- 14.27065
p + geom_bar(stat = "identity") +
geom_segment(aes(x=0, xend=.1, y=avg.y, yend=avg.y))

with line

最佳答案

在条形图中,条形(隐式)以 1 和 2 为中心,并在任一方向上延伸约 +/- 0.45。因此,您可以更改段的 x 范围以将其定位在您想要的位置。

ggplot(df, aes(x, y)) +
geom_bar(stat="identity") +
geom_segment(aes(x=0.5, xend=2.5, y=avg.y, yend=avg.y), colour="red") +
theme_bw()

enter image description here

为了回应您的评论,让我们使用 ggplot_build 查看原始图的底层结构。 .现在让我们看看 data pb 的元素.请注意,在第一个数据框中,即条形的内部绘图数据,条形位于 x=1 和 x=2 处。 xminxmax显示条宽的范围。第二个数据帧是内部段定位。该段的位置从 x=0 到 x=0.1。因此,0.1(线段的右边缘)和 0.45( FALSE 条的左边缘)之间没有任何值,这可以在您在问题中发布的第二个图中看到。
p = ggplot(df, aes(x, y)) +
geom_bar(stat="identity") +
geom_segment(aes(x=0, xend=0.1, y=avg.y, yend=avg.y))

pb = ggplot_build(p)
pb$data

[[1]]
x y PANEL group ymin ymax xmin xmax colour fill size linetype alpha
1 1 13.02040 1 1 0 13.02040 0.55 1.45 NA grey35 0.5 1 NA
2 2 14.37956 1 2 0 14.37956 1.55 2.45 NA grey35 0.5 1 NA

[[2]]
x xend y yend PANEL group colour size linetype alpha
1 0 0.1 14.27065 14.27065 1 -1 red 0.5 1 NA
2 0 0.1 14.27065 14.27065 1 -1 red 0.5 1 NA

关于r - ggplot : bar positions shifted right with geom_segment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47851252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com