Search code examples
rggplot2legendlegend-properties

ggplot2 legend width and legend strings size


I have 2 plots of the exact same thing, excepts the colors filling the bars are different on each plot. Since the legend on the different plots have different widths because of the size of the names on it, the ratio between graph and legend becomes different on each plot. I need to make both look the same.

This is an example:

library(ggplot2)

x = c(rep("a",20),rep("b",10))
y = c(x = c(rep("BIGTEXT",20),rep("EVENBIGGERTEXT",10)))
df = data.frame(x,y)

p1 = ggplot(df,aes(x,fill=x)) + geom_bar()
p2 = ggplot(df,aes(y,fill=y)) + geom_bar()

p1
p2

Solution

  • You can set the gtable widths to a common value,

    library(gtable)
    library(grid)
    gl <- lapply(list(p1, p2), ggplotGrob)
    
    gwidth <- do.call(unit.pmax, lapply(gl, "[[", "widths"))
    gl <- lapply(gl, "[[<-", "widths", value = gwidth)
    gridExtra::grid.arrange(grobs=gl)
    

    Alternatively, you can set the panel size to a fixed value.