Search code examples
rggplot2scalebar-chart

Create ggplots with the same scale in R


I'd like to do the following in R: I have 2 datasets (one consisting of 4, the other of 3 values) and I'd like to plot them with ggplot2 as bar charts (separately). However, I'd like to use the same scale for the both, i.e.: if the minimum value of dataset #1 is 0.2 and 0.4 of dataset #2, then I want to use 0.2 for both. Same applies for the maximum values (choosing the greater there).

So, basically, I want to make the 2 plots comparable. Of course, would be great to apply the common scale for coloring the bars, as well. Now, I'm using colorRampPalette and applying it in the scale_fill_gradient2 property.

A MWE provided below:

library("ggplot2")
val <- c(0.2, 0.35, 0.5, 0.65)
labels <- c('A', 'B', 'C', 'D')

LtoM <-colorRampPalette(c('green', 'yellow'))

df <- data.frame(val)
bar <- ggplot(data = df,
              aes(x = factor(labels),
                  y = val,
                  fill = val)) +
  geom_bar(stat = 'identity') + 
  scale_fill_gradient2(low=LtoM(100), mid='snow3', 
                       high=LtoM(100), space='Lab') +
  geom_text(aes(label = val), vjust = -1, fontface = "bold") +
  labs(title = "Title", y = "Value", x = "Methods") +
  theme(legend.position = "none")
print(bar)

Given the code above, and another dataset like c(0.4, 0.8, 1.2) with labels c('E', 'F', 'G'), how to adjust the code to create 2 different and separated plots (saved into PNGs finally, i.e.) but use the common (0.2 to 1.2) scale for both the heights of bars and their colors (so moving the images exactly next to each other indicates that the bars with the same height but belonging to different images appear in the same way and their colors are the same)?


Solution

  • We can use a mix of the breaks argument in scale_y_continuous to ensure that we have consistent axis ticks, then use coord_cartesian to ensure that we force both plots to have the same y-axis range.

    df1 <- data.frame(val = c(0.2, 0.35, 0.5, 0.65), labels = c('A', 'B', 'C', 'D'))
    df2 <- data.frame(val = c(0.4, 0.8, 1.2), labels = c('E', 'F', 'G'))
    
    g_plot <- function(df) {
        ggplot(data = df,
              aes(x = factor(labels),
                  y = val,
                  fill = val)) +
            geom_bar(stat = 'identity') + 
            scale_fill_gradient2(low=LtoM(100), mid='snow3', 
                         high=LtoM(100), space='Lab') +
            geom_text(aes(label = val), vjust = -1, fontface = "bold") +
            scale_y_continuous(breaks = seq(0, 1.2, 0.2)) + 
            coord_cartesian(ylim = c(0, 1.2)) + 
            labs(title = "Title", y = "Value", x = "Methods") +
            theme(legend.position = "none")
    }
    
    bar1 <- g_plot(df1);
    bar2 <- g_plot(df2);
    gridExtra::grid.arrange(bar1, bar2, ncol = 2);
    

    Example