AneesBaqir
AneesBaqir

Reputation: 453

How to create plots with same widths (excluding legend) with grid.arrange

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 here, but it maintains the width of both plots including legend text. Therefore the actual width of the plots remains unequal.

Can someone please guide me on this?

Upvotes: 1

Views: 1031

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You could add some spacing legend labels of plot A. This will also keep the legend key boxes nicely aligned, and the labels effectively right-justified.

#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") +
  theme(legend.spacing.x = unit(6.1, 'mm'))


# 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(A, B), ncol=1, common.legend = TRUE, legend="bottom",
             top = title, widths = unit(0.9, "npc"))

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))

Upvotes: 1

Related Questions