代码之家  ›  专栏  ›  技术社区  ›  Adrian

R:如何将对角线添加到ggplot中的装箱图中

  •  2
  • Adrian  · 技术社区  · 3 年前
    # 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度的对角线。这会产生一条黑线。然而,这与实际情况并不完全相符 bin 在x轴上。例如,当 bin = (2.5,3] ,黑线的y坐标为6。

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

    enter image description here

    1 回复  |  直到 3 年前
        1
  •  2
  •   Axeman    3 年前

    对于 ggplot ,轴上的任何类别的距离都为1。所以 geom_abline 坡度为1时,每个类别的y轴将增加1。由于您的垃圾箱大小为1/2,因此使用的坡度为 0.5 将正确绘制坡度。

    我们还需要将截距调整到 -0.25 这是因为第一个箱子位于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))
    

    请注意,我还画了两条水平线,以确认这符合手动计算出的示例值。

    enter image description here