R:如何向 ggplot 中的分箱箱线图添加对角线

标签 r ggplot2 data-visualization 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。

我粗略地画了(蓝色)我认为 45 度对角线应该在的位置。例如,对于 bin = (2.5, 3],y 坐标应为 2.75(bin 的中点)。对于 bin = (3, 3.5], y 坐标应该是 3.25(bin 的中点)。有没有办法在 ggplot 中生成这条线?

enter image description here

最佳答案

对于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 条水平线以确认这适合您手动计算出的示例值。

enter image description here

关于R:如何向 ggplot 中的分箱箱线图添加对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72050706/

相关文章:

r - 将一系列相似长度向量与 NA 合并为一个向量

r - 使用 geom_smooth 进行对数插值

python - 如何在python中将属性附加到geojson文件?

javascript - Google Visualization API 双 Y 轴 - 无法调整 targetAxisIndex

r - 询问如何在 R 中使用 ggplot 制作世界热图?

r - 是否可以在没有 %% 的情况下定义运算符?

list - 在 R 中解压省略号的参数列表

r - 如何在 facet_grid 中改变线条和色带颜色

r - 如何从标签剪切间隔中删除 E 符号并用速记标签替换?

r - ggplot2 对齐两个分面图的顶部