I've got a few different categories that I want to plot. These are different categories, each with their own set of labels, but which makes sense to group together in the document. The following gives some simple stacked bar chart examples:
df <- data.frame(x=c("a", "b", "c"),
y=c("happy", "sad", "ambivalent about life"))
ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()
The problem is that with different labels, the legends have different widths, which means the plots have different widths, leading to things looking a bit goofy if I make a table or \subfigure
elements. How can I fix this?
Is there a way to explicitly set the width (absolute or relative) of either the plot or the legend?
I created a little function based on the answer of @Sandy.
Before
After
The
cowplot
package also has thealign_plots
function for this purpose (output not shown),and also
plot_grid
which saves the plots to the same file.Just by chance, I noticed that Arun's solution he had suggested in his comments hasn't been picked up. I feel his simple and efficient approach is really worth to be illustrated.
Arun suggested to move the legend to the top or bottom:
Now, the plots have the same width as requested. In addition, the plot area is equally sized in both cases.
If there are more factors or even longer labels, it might become necessary to play around with the legend, e.g., to display the legend in two ore more rows.
theme()
andguide_legend()
have several parameters to control the position and appearance of legends inggplot2
.As @hadley suggests,
rbind.gtable
should be able to handle this,however, the layout widths should ideally be
size="max"
, which doesn't cope well with some types of grid units.Edit: Very easy with
egg
package available at githubOriginal Udated to ggplot2 2.2.1
Here's a solution that uses functions from the
gtable
package, and focuses on the widths of the legend boxes. (A more general solution can be found here.)If in addition, the legend boxes need to be left justified, and borrowing some code from here written by @Julius
Alternative solutions There are
rbind
andcbind
functions in thegtable
package for combining grobs into one grob. For the charts here, the widths should be set usingsize = "max"
, but the CRAN version ofgtable
throws an error.One option: It should be obvious that the legend in the second plot is wider. Therefore, use the
size = "last"
option.Left-aligned legends:
A second option is to use
rbind
from Baptiste'sgridExtra
packageLeft-aligned legends: