Home > Enterprise >  Change panel width ggplot2
Change panel width ggplot2

Time:05-31

I am creating some plots with ggplot2 and I would like to add stats to it post-hoc. However, I have the issue that the plot ends so close to the margin that I don't have space to add it. Here is a picture:

enter image description here

I would like to draw the stars etc at the right hand side of each plot. So I would like to just have some extra space at the right hand side of each panel. I have been trying to find a command for that but it hasn't been going well...

Here is the code I'm using to plot:

df %>% 
  group_by(group, animal, day, zone) %>%
  summarise(sum_cum = sum(cum_time_sec)) %>%
  ggline(x='day', y='sum_cum', color = 'group', fill = ' group', size = 1.1, outlier.shape = NA,
         add = c("mean_se"), add.params = list(alpha=0.5), point.size = 4, linetype = 1, facet.by = "zone", ncol = 4)

Thank you!

CodePudding user response:

Without data, it's always more difficult to show a working solution, but we can replicate your plot approximately by doing:

library(ggpubr)
library(dplyr)

df <- data.frame(group = rep(c('A', 'B'), each = 20),
           animal = 1, day = rep(1:5, 8), zone = rep(rep(1:4, each = 5), 2),
           cum_time_sec = c(5, 10, 11, 10, 8, 10, 9, 8, 7, 8, 40, 35, 37, 
                            39, 41, 5, 4, 3, 4, 5, 4, 4, 4, 5, 3, 10, 6, 7, 
                            8, 6, 40, 45, 44, 45, 49, 4, 3, 4, 2, 1))

p <- df %>% 
  group_by(group, animal, day, zone) %>%
  summarise(sum_cum = sum(cum_time_sec)) %>%
  ggline(x='day', y='sum_cum', color = 'group', fill = ' group', 
         size = 0.5, outlier.shape = NA,
         add = c("mean_se"), add.params = list(alpha=0.5), 
         point.size = 1, linetype = 1, facet.by = "zone", ncol = 4)  
  scale_color_manual(values = c('#1064bc', '#afafaf')) 

p

enter image description here

To increase panel spacing, we simply use the panel.spacing.x theme element:

p   theme(panel.spacing.x = unit(15, 'mm'))

enter image description here

If you want extra space after the last point, simply change the x axis limits:

p   scale_x_continuous(breaks = 1:5, limits = c(1, 7))

enter image description here

CodePudding user response:

Another option is to use multiple expansions in scale_continuous.

## I am using Allan's carefully produced plot `p`. 
## Thanks, Allan  1

p   
  scale_x_continuous(breaks = 1:5, expand = expansion(mult = c(0, .4)))

  • Related