R:如何将对角线添加到GGPLOT中的Binned Boxplot
# library
library(ggplot2)
library(dplyr)
# Start with the diamonds dataset, natively available in R:
p <- diamonds %>%
# Add a new column called 'bin': cut the initial 'carat' in bins
mutate(bin=cut_width(carat, width = 0.5, boundary=0) ) %>%
# plot
ggplot(aes(x=bin, y= x) ) +
geom_boxplot() +
xlab("Carat") + geom_abline(slope = 1, intercept = 0)
p
我尝试使用geom_abline
添加45度对角线。这会产生黑线。但是,这与X轴上的bin
完全不完全匹配。 ,当bin =(2.5,3]
时,黑线的y坐标为6。
例如 ,对于bin =(2.5,3]
,y坐标应为2.75(bin的中点)。对于bin =(3,3.5]
,y - 涂层应为3.25(bin的中点)
。 >
# library
library(ggplot2)
library(dplyr)
# Start with the diamonds dataset, natively available in R:
p <- diamonds %>%
# Add a new column called 'bin': cut the initial 'carat' in bins
mutate(bin=cut_width(carat, width = 0.5, boundary=0) ) %>%
# plot
ggplot(aes(x=bin, y= x) ) +
geom_boxplot() +
xlab("Carat") + geom_abline(slope = 1, intercept = 0)
p
I tried using geom_abline
to add a 45-degree diagonal line. This produces a black line. However, this does not exactly match with the bin
on the x-axis. For example, when bin = (2.5,3]
, the black line's y-coordinate is at 6.
I roughly drew (in blue) where I think the 45-degree diagonal line should be. For example, for bin = (2.5, 3]
, the y-coordinate should 2.75 (mid-point of the bin). For bin = (3, 3.5]
, the y-coordinate should be 3.25 (mid-point of the bin). Is there a way to produce this line in ggplot?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于
ggplot
,轴上的任何类别的距离为1。因此,geom_abline
以1的斜率为1,每个类别的1个都会增加y轴。由于您的垃圾箱的尺寸为1/2,因此使用0.5
的坡度将正确绘制斜率。我们还需要将截距调整为
-0.25
。这是因为第一个垃圾箱在x坐标1,而不是0.25。请注意,我还绘制了2条水平线,以确认这适合您手动验证的示例值。
For
ggplot
, any categories on an axis have a distance of 1. Sogeom_abline
with a slope of 1 will increase your y-axis with 1 for each category. Since your bins are of size 1/2, using a slope of0.5
will draw the slope correctly.We also need to adjust the intercept to
-0.25
. This is because the first bin is at x-coordinate 1, not 0.25.Note that I also drew 2 horizontal lines to confirm that this fits your manually worked out example values.