# 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。
我粗略地画了(蓝色)我认为 45 度对角线应该在的位置。例如,对于 bin = (2.5, 3]
,y 坐标应为 2.75(bin 的中点)。对于 bin = (3, 3.5]
, y 坐标应该是 3.25(bin 的中点)。有没有办法在 ggplot 中生成这条线?
最佳答案
对于ggplot
,轴上的任何类别的距离均为 1。因此,斜率为 1 的 geom_abline
会将每个类别的 y 轴增加 1。由于您的分箱尺寸为 1/2,因此使用 0.5
的斜率将正确绘制斜率。
我们还需要将截距调整为-0.25
。这是因为第一个 bin 位于 x 坐标 1,而不是 0.25。
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 = 0.5, intercept = -0.25) +
geom_hline(yintercept = c(2.75, 3.25))
请注意,我还画了 2 条水平线以确认这适合您手动计算出的示例值。
关于R:如何向 ggplot 中的分箱箱线图添加对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72050706/