Home > front end >  How to create plots with same widths (excluding legend) with grid.arrange
How to create plots with same widths (excluding legend) with grid.arrange

Time:04-12

I have created the plot below where the width of two plots is not same because the text length in the legend exceeds in Plot B. enter image description here

I am using the following code:

#Plot A
A<- ggplot(df_a, aes(x=Timestamp, y=Frequency, fill=Topic))   
  scale_x_date(date_breaks = '1 month', date_labels = "%b") 
  geom_area(alpha=0.6 , size=1, colour="black", position = position_fill()) 
  ggtitle("Plot A")


# Plot B
B<- ggplot(df_b, aes(x=Timestamp, y=Frequency, fill=Topic))   
  scale_x_date(date_breaks = '1 month', date_labels = "%b") 
  geom_area(alpha=0.6 , size=1, colour="black", position = position_fill()) 
  ggtitle("Plot B")

title=text_grob("", size = 13, face = "bold") #main title of plot
grid.arrange(grobs = list(R,Q), ncol=1, common.legend = TRUE, legend="bottom",
             top = title, widths = unit(0.9, "npc"))

I am even using widths = unit(0.9, "npc") as suggested enter image description here


Packages and data used

library(gridExtra)
library(ggplot2)
library(ggpubr)

set.seed(1)

df_a <- data.frame(Timestamp = rep(seq(as.Date('2022-01-01'), 
                                       as.Date('2022-12-01'),
                                       by = 'month'), 5),
                   Frequency = runif(60, 0.1, 1),
                   Topic = rep(LETTERS[1:5], each = 12))

df_b <- data.frame(Timestamp = rep(seq(as.Date('2022-01-01'), 
                                       as.Date('2022-12-01'),
                                       by = 'month'), 5),
                   Frequency = runif(60, 0.1, 1),
                   Topic = rep(c('AAA', 'BBB', 'CCC', 'DDD', 'EEE'), each = 12))

  • Related