Search code examples
rbar-chartdifference

Side by side barplots in r


I have a data set that looks like this data

I want to create side by side barplots that will show the differences between the two grades, I envisioned something like this

barplot

Any help would be highly appreciated.


Solution

  • In base R, you can use barplot to iteratively lay over the values through a series of par(new = TRUE) and ifelse logic. You can add the text with similar logic using text:

    par(mfrow = c(1,2)) #side by side plot
    # left plot
    barplot(df$Grade_Semester1, names.arg = df$Person, horiz = TRUE, col = "grey", xlim = c(0, 10))
    
    # right plot
    barplot(ifelse(df$Difference < 0, df$Grade_Semester1, 0), 
            names.arg = df$Person, horiz = TRUE, col = "red", xlim = c(0, 10))
    par(new = TRUE)
    barplot(ifelse(df$Difference > 0, df$Grade_Semester2, 0), 
            names.arg = df$Person, horiz = TRUE, col = "green", xlim = c(0, 10))
    par(new = TRUE)
    xx <- barplot(pmin(df$Grade_Semester1, df$Grade_Semester2), 
            names.arg = df$Person, horiz = TRUE, col = "grey", xlim = c(0, 10))
    
    text(pmin(df$Grade_Semester1, df$Grade_Semester2) + abs(pmin(df$Difference)/2),
         xx, ifelse(df$Difference == 0, "", ifelse(df$Difference > 0, paste0("+", df$Difference), df$Difference)))
    

    enter image description here

    Data

    df <- data.frame(Person = c("A", "B", "C"),
                     Grade_Semester1 = c(9, 10, 8),
                     Grade_Semester2 = c(7, 10, 10),
                     Difference = c(-2, 0, 2))