如何使用ggplot2制作基本的R风格箱形图?

时间:2018-11-06 10:54:34

标签: r ggplot2 boxplot

我需要为即将出版的出版物制作很多箱型图。我想使用ggplot2,因为我认为它对于将来的项目将更加灵活,但是我的PI坚持要求我以base-R的样式进行绘制。他特别想要虚线,以便它们看起来与我们之前绘制的情节相似。我使用以下代码通过虹膜数据集向您展示了一个示例:

plot(iris$Species,
     iris$Sepal.Length,
     xlab='Species',
     ylab='Sepal Length',
     main='Sepal Variation Across Species',
     col='white')

base R plot

我的问题是如何使用ggplot2绘制相似外观的图?

这是我的尝试:

library("ggplot2")
ggplot(iris) +
  geom_boxplot(aes(x=Species,y=Sepal.Length),linetype="dashed") +
  ggtitle("Sepal Variation Across Species")

ggplot attempt

我需要虚线和实线的组合,但是我什么也做不了。我已经检查过https://stats.stackexchange.com/questions/8137/how-to-add-horizontal-lines-to-ggplot2-boxplot,它非常接近但没有虚线,这是我们需要的。另外,异常值是实心圆,与base-R不同。

3 个答案:

答案 0 :(得分:11)

要使用ggplot2生成“基本R风格”箱线图,我们可以将4个箱线图对象彼此叠加。 这里的顺序很重要,因此,如果您修改代码,请记住这一点。我强烈建议您通过自己绘制每个boxplot图层来探索此代码。这样,您可以了解不同图层之间的交互方式。

箱形图的排序是这样的(从下到上排序):

  • (1)垂直虚线放在第一位
  • (2)包含中线的实心框,覆盖了(1)
  • 中的虚线框
  • (3)(4)实晶须线,通过使用将最小值设置为最大值的误差线创建,反之亦然。

我还添加了自定义休息时间以匹配您的基本R图,您可以根据需要进行更改。 panel.border用于创建基本R样式的细边框。要获得所需的空心圆,我们使用outlier.shape

代码:

library("ggplot2")

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot(linetype = "dashed", outlier.shape = 1) +
  stat_boxplot(aes(ymin = ..lower.., ymax = ..upper..), outlier.shape = 1) +
  stat_boxplot(geom = "errorbar", aes(ymin = ..ymax..)) +
  stat_boxplot(geom = "errorbar", aes(ymax = ..ymin..)) +
  scale_y_continuous(breaks = seq(4.5, 8.0, 0.5)) +
  labs(title = "Sepal Variation Across Species",
       x = "Species",
       y = "Sepal Length") +
  theme_classic() + # remove panel background and gridlines
  theme(plot.title = element_text(hjust = 0.5,  # hjust = 0.5 centers the title
                                  size = 14,
                                  face = "bold"),
        panel.border = element_rect(linetype = "solid",
                                    colour = "black", fill = "NA", size = 0.5))

情节:

enter image description here

不是完全相同,但似乎是一个不错的近似值。希望这足够满足您的需求。祝你好运,快乐的情节!

答案 1 :(得分:3)

这里是@Marcus出色解决方案的包装,以方便使用和提供更大的灵活性:

geom_boxplot2 <- function(mapping = NULL, data = NULL, stat = "boxplot", position = "dodge2", 
                          ..., outlier.colour = NULL, outlier.color = NULL, outlier.fill = NULL, 
                          outlier.shape = 1, outlier.size = 1.5, outlier.stroke = 0.5, 
                          outlier.alpha = NULL, notch = FALSE, notchwidth = 0.5, varwidth = FALSE, 
                          na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,
                          linetype = "dashed"){
  list(
    geom_boxplot(mapping = mapping, data = data, stat = stat, position = position,
                 outlier.colour = outlier.colour, outlier.color = outlier.color, 
                 outlier.fill = outlier.fill, outlier.shape = outlier.shape, 
                 outlier.size = outlier.size, outlier.stroke = outlier.stroke, 
                 outlier.alpha = outlier.alpha, notch = notch, 
                 notchwidth = notchwidth, varwidth = varwidth, na.rm = na.rm, 
                 show.legend = show.legend, inherit.aes = inherit.aes, 
                 linetype = linetype, ...),
    stat_boxplot(aes(ymin = ..lower.., ymax = ..upper..), outlier.shape = 1) ,
    stat_boxplot(geom = "errorbar", aes(ymin = ..ymax..)) ,
    stat_boxplot(geom = "errorbar", aes(ymax = ..ymin..)) ,
    theme_classic(), # remove panel background and gridlines
    theme(plot.title = element_text(hjust = 0.5,  # hjust = 0.5 centers the title
                                    size = 14,
                                    face = "bold"),
          panel.border = element_rect(linetype = "solid",
                                      colour = "black", fill = "NA", size = 0.5))
  )
}

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot2() +
  scale_y_continuous(breaks = seq(4.5, 8.0, 0.5)) + # not sure how to generalize this
  labs(title = "Sepal Variation Across Species", y = "Sepal Length")

答案 2 :(得分:1)

进一步构建@Marcus和@Moody_Mudskipper提供的内容:

``` r
geom_boxplotMod <- function(mapping = NULL, data = NULL, stat = "boxplot", 
    position = "dodge2", ..., outlier.colour = NULL, outlier.color = NULL, 
    outlier.fill = NULL, outlier.shape = 1, outlier.size = 1.5, 
    outlier.stroke = 0.5, outlier.alpha = NULL, notch = FALSE, notchwidth = 0.5,
    varwidth = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE,
    linetype = "dashed") # to know how these come here use: args(geom_boxplot)
    {
    list(geom_boxplot(
            mapping = mapping, data = data, stat = stat, position = position,
            outlier.colour = outlier.colour, outlier.color = outlier.color, 
            outlier.fill = outlier.fill, outlier.shape = outlier.shape, 
            outlier.size = outlier.size, outlier.stroke = outlier.stroke, 
            outlier.alpha = outlier.alpha, notch = notch, 
            notchwidth = notchwidth, varwidth = varwidth, na.rm = na.rm, 
            show.legend = show.legend, inherit.aes = inherit.aes, linetype = 
            linetype, ...),
        stat_boxplot(geom = "errorbar", aes(ymin = ..ymax..), width = 0.25),
        #the width of the error-bar heads are decreased
        stat_boxplot(geom = "errorbar", aes(ymax = ..ymin..), width = 0.25),
        stat_boxplot(aes(ymin = ..lower.., ymax = ..upper..),
            outlier.shape = 1),
        theme(panel.background = element_blank(),
            panel.border = element_rect(size = 1.5, fill = NA),
            plot.title = element_text(hjust = 0.5),
            axis.title = element_text(size = 12),
            axis.text = element_text(size = 10.5))
        )
    }

library(tidyverse); library(ggplot2);
ggplot(iris, aes(x=Species,y=Sepal.Length, colour = Species)) +
    geom_boxplotMod() +
    ggtitle("Sepal Variation Across Species")

reprex package(v0.3.0)于2020-07-20创建