简体   繁体   中英

Add horizontal bars to whiskers on percentile based boxplot

I have my data and plot as:

new_df <- structure(list(Group = c("k__Fungi; p__Ascomycota; c__Eurotiomycetes; o__Chaetothyriales; f__Chaetothyriaceae; g__unidentified", 
"k__Fungi; p__Ascomycota; c__Eurotiomycetes; o__Chaetothyriales; f__Chaetothyriaceae; g__unidentified", 
"k__Fungi; p__Ascomycota; c__Eurotiomycetes; o__Chaetothyriales; f__Chaetothyriaceae; g__unidentified", 
"k__Fungi; p__Ascomycota; c__Eurotiomycetes; o__Chaetothyriales; f__Chaetothyriaceae; g__unidentified"
), Percentile_0 = c(1, 1, 1, 1), Percentile_25 = c(1, 17.75, 
8, 99.5), Percentile_50 = c(1, 48, 32, 215.5), Percentile_75 = c(3, 
93, 51.25, 343.75), Percentile_100 = c(28, 337, 104, 788), Type = c("T1", 
"T2", "T3", "T4")), row.names = c(NA, -4L), class = "data.frame")


#plot 
ggplot(data = new_df, aes(x =Group, group = Type, fill = Type)) +
    geom_boxplot(
      stat = "identity",
      aes(
        ymin = Percentile_0,
        lower = Percentile_25,
        middle = Percentile_50,
        upper = Percentile_75,
        ymax = Percentile_100
      )
    ) +
    theme_classic()

在此处输入图片说明

I would like to add horizontal whiskers as stated in this thread here .

Since you have already calculated the values for the ends of the whiskers you can use geom_errorbar() directly rather than via stat_boxplot() as in the link you gave.

You will need to explicitly dodge the error bars to match the default dodging of the boxplots.

The required aesthetics for geom_errobar() are ymin and ymax . I put these within the geom_errorbar() layer. since you use these for both the boxplots and the errorbars you could move them up to the global aes() to avoid repetition.

ggplot(data = new_df, aes(x = Group, group = Type, fill = Type)) +
    geom_errorbar(aes(ymin = Percentile_0, 
                      ymax = Percentile_100), 
                  width = 0.5, 
                  position = position_dodge(width = 0.9) ) +
    geom_boxplot(
        stat = "identity",
        aes(
            ymin = Percentile_0,
            lower = Percentile_25,
            middle = Percentile_50,
            upper = Percentile_75,
            ymax = Percentile_100
        )
    ) +
    theme_classic()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM