Search code examples
rggplot2labelwidth

Same width of y labels in multiple plots with ggplot


I want to generate an output of x plots with ggplot on differennt pages. The y labels are text variables with different lengths. Depending on the max. length of these labels the plots are not looking the same, label and diagram area are automatically optimized by ggplot. There should be a way to have always the same width for the y labels or not? page 1

page 2

Code fragment of ggplot command:

print(ggplot(dfPriceArt[ixStart:ixEnde, ], aes(x=reorder(BATArtikelKomplett, MaxEinzelpreisPerc), y=MaxEinzelpreisPerc, size=MaxEinzelpreisPerc)) + 
geom_point() +
coord_flip() +
labs(y='BATArtikel',x='MaxEinzelpreis') +
theme(axis.text=element_text(size=6)) +
scale_y_continuous(limits=c(100, maxEinzelpreisPerc)) +
scale_size_continuous(limits=c(100, maxEinzelpreisPerc)))

Solution

  • The first comment to left align two graph edges (ggplot) helped a lot to find an own solution additionally with Align multiple plots in ggplot2 when some have legends and others don't (last edit).

    As @Jimbou pointed out I wanted to have one plot per page, sorry to have not mentioned that.

    This is what my solution now looks like:

    library(gridExtra)
    ...
    for (i in 1:iLast) {
        ...
        p <- ggplot(dfPriceArt[ixStart:ixEnde, ], aes(x=reorder(BATArtikelKomplett, MaxEinzelpreisPerc), y=MaxEinzelpreisPerc, size=MaxEinzelpreisPerc)) + 
            geom_point() +
            coord_flip() +
            labs(y='BATArtikel',x='MaxEinzelpreis') +
            theme(axis.text=element_text(size=6)) +
            scale_y_continuous(limits=c(100, maxEinzelpreisPerc)) +
            scale_size_continuous(limits=c(100, maxEinzelpreisPerc))
        plot_list[[i]] <- ggplotGrob(p)
        widths_list[[i]] <- plot_list[[i]]$widths[2:5]
        ...
    }
    maxWidth <- do.call(grid::unit.pmax, widths_list)
    for (i in 1:iLast) {
      plot_list[[i]]$widths[2:5] <- as.list(maxWidth)
      grid.draw(plot_list[[i]])
      if (i != iLast) {
        grid.newpage()
      }
    }