Dynamic axis ticks at top and bottom of plot area with consistent number of intervals and consistent width when looping (ggplot2, grid.arrange)

Viewed 72

I have some data

set.seed(123)

df <- data.frame(rbind(
  a = rnorm(4, 60, 30),
  b = rnorm(4, 30, 15),
  c = rnorm(4, 10, 5))) 

spe_a  = rnorm(3, mean=0.05, sd=0.003)
season = factor(c('Jan','Feb','Mar'))

colnames(df) <- c("spe_b","spe_c","spe_d","spec_e")
df <- cbind(season, spe_a, df) 
# Yes I am sure there is a better method! Please advise in comments?
# I was determine to recreate my problem 

Using the following I can produce a gridded plot:

plot_list = list()

library(ggplot2)

for(i in colnames(df[, 2:5])){
  #
  plot <- ggplot(data = df,
                 aes_string(x = df$season, y = i)) +
    geom_bar(stat = 'identity',
             fill = 'lightblue') + # For style
    ggtitle(i) + 
    theme(axis.title.y = element_blank()) +
    scale_y_continuous(expand = c(0,0))
  #
  plot_list[[i]] = plot
  #
}

library(gridExtra)

grid.arrange(grobs = plot_list, ncol = 2)

This gives me: enter image description here

Great! But its got a few issues (see fig. 2 also)

  1. I want the ticks (and labels) to always be at the top and bottom of the plot area.
  2. I want the ticks to have a consistent number of intervals (well at least somewhat 4/5)
  3. The plots need to have the same plot area.

enter image description here

I know there are a few questions in here but I think they may be related.

I did have a good look around

1 Answers

Try this approach with patchwork and setting breaks using seq(). Here the code:

library(patchwork)
library(ggplot2)
#List
plot_list = list()
#Loop
for(i in colnames(df[, 2:5])){
  #
  plot <- ggplot(data = df,
                 aes_string(x = season, y = i)) +
    geom_bar(stat = 'identity',
             fill = 'lightblue') + # For style
    ggtitle(i) + 
    theme(axis.title.y = element_blank()) +
    scale_y_continuous(expand = c(0,0),
                       limits = c(0, max(df[,i])),
                       breaks = seq(0,max(df[,i]),length.out = 5),
                       labels = function(x) round(x,2))
  #
  plot_list[[i]] = plot
  #
}
#Plot
G <- wrap_plots(plot_list,ncol = 2)

Output:

enter image description here

Related