Search code examples
rggplot2geom-bargeom

how to add multiples lines in a single bar using geom_bar and geom_errorbar in R


I want to add multiples lines using geom_errorbar in a single bar with geom_bar with ggplot2 in R

I used an example similar to: https://ggplot2.tidyverse.org/reference/geom_linerange.html

df <- data.frame(
    resp = c(50, 50, 50, 50),
    group = factor(c("G1", "G2", "G3", "G4")),
    upper = c(40, 49, 33, 42)
)

if I use the data frame to plot

ggplot(df, aes(x=group, y=resp, fill = group)) + 
    geom_bar(stat = "identity") +
    geom_errorbar(aes(ymin = upper, ymax = upper), size = 0.5, linetype=1, alpha=1, color="white")

it will generate a single line per bar

enter image description here

so if I use the next data frame with multiples lines in upper column

df2 <- data.frame(
    resp = rep(c(50, 50, 50, 50),4),
    group = factor( rep(c("G1", "G2", "G3", "G4"), 4)), 
    upper = c(10, 17, 49, 40, 40, 33, 42, 47, 29, 25, 33, 41, 49, 22, 32, 33)
)

then plot it

ggplot(df2, aes(x=group, y=resp, fill = group)) + 
    geom_bar(stat = "identity") +
    geom_errorbar(aes(ymin = upper, ymax = upper), size = 0.5, linetype=1, alpha=1, color="white")

it will add multiples lines, but the bars in Y axis up to 200!!

How can I fix it, just to get to 50 in Y axis instead to 200?

enter image description here

do I have to use 2 data frames ?

Thanks !!!


Solution

  • The issue with your second trial is that you have multiple resp values per group which by default get stacked and each bars sums to 200 = 4 x 50. Instead I would suggest to use two separate data frames, one for the bars, one for the lines:

    library(ggplot2)
    
    df_bars <- data.frame(
      resp = c(50, 50, 50, 50),
      group = factor(c("G1", "G2", "G3", "G4"))
    )
    
    df_lines <- data.frame(
      group = factor(rep(c("G1", "G2", "G3", "G4"), 4)),
      upper = c(10, 17, 49, 40, 40, 33, 42, 47, 29, 25, 33, 41, 49, 22, 32, 33)
    )
    
    ggplot(mapping = aes(x = group)) +
      geom_col(aes(y = resp, fill = group), data = df_bars) +
      geom_errorbar(aes(ymin = upper, ymax = upper), data = df_lines, 
                    size = 0.5, linetype = 1, alpha = 1, color = "white")