【问题标题】:positioning horizontal boxplots in ggplot2在ggplot2中定位水平箱线图
【发布时间】:2012-09-27 17:11:19
【问题描述】:

我正在尝试在 ggplot2 中绘制水平箱线图,您只能通过使用 coord_flip() 来完成。我还尝试将箱线图垂直隔开以将某些集合组合在一起。我已经读过这种事情推荐使用刻面,但这与 coord_flip() 不兼容,我们可以在这里看到:ggplot2: boxplot with facet_grid and free scale。所以我想知道是否可以使用空白级别来创建空格。以下是我到目前为止所做的:

d <- diamonds
library("ggplot2")
levels(d$cut) <- list(A="Fair", B="Good", "-", C="Very Good", D="Ideal", E="Premium")
p = ggplot(d, aes(x=cut, y=depth))
p + 
    geom_boxplot(color="black", size=0.2) + 
    theme_bw() + 
    scale_x_discrete(breaks = c("A", "B", "-", "C", "D", "E"), drop=FALSE) +
    coord_flip()

ph = 2.75
pw = 4
ggsave("plot.png", height=ph, width=pw)

如您所见,如果我在其中创建一个带有“-”的空白级别并将其包含在 scale_x_discrete() 中,那么我会以某种方式得到一个空白行。问题是我只能添加一个空格。有人对如何在这些水平箱形图之间添加空格有任何想法吗?

【问题讨论】:

    标签: r ggplot2 boxplot


    【解决方案1】:

    这是一种可以让您添加更多空白级别的方法:

    d <- diamonds
    levels(d$cut) <- list(A="Fair", B="Good", " "="space1", C="Very Good", D="Ideal", "  "="space2", E="Premium")
    ggplot(d, aes(x=cut, y=depth)) +
      geom_boxplot(color="black", size=0.2) + 
      theme_bw() + 
      scale_x_discrete(breaks = c("A", "B", " ", "C", "D", "  ", "E"), drop=FALSE) +
      coord_flip()
    

    不过,这也会在垫片上留下刻度线:

    删除所有刻度很简单,只需添加:

    + theme(axis.ticks.y = element_line(linetype=0))
    

    但是,如果您只想删除分隔符的刻度线,至少有一种方法(我相信还有其他方法)是使用自定义函数:

    f <- function(x) {
      x[!x %in% c("A", "B", "C", "D", "E")] <- NA
      x
    }
    
    ggplot(d, aes(x=cut, y=depth)) +
      geom_boxplot(color="black", size=0.2) + 
      theme_bw() + 
      scale_x_discrete(breaks=f, drop=FALSE) +
      coord_flip()
    

    【讨论】:

    • 如果有人很难看出区别,那就是 y 轴上的刻度线和网格线。
    猜你喜欢
    • 2016-03-25
    • 2019-01-31
    • 2021-03-03
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2021-09-23
    • 2016-10-27
    相关资源
    最近更新 更多