Skip to content

Theme option to align the legend to the plot instead of the panel #5959

Closed
@sambtalcott

Description

@sambtalcott

I often use the plot.title.position = "plot" argument to theme() to get my plot's title to align to the plot rather than the panel. This is especially helpful when the y-axis labels are long.

I sometimes want to add a horizontal legend to the top of charts like this. However, there is no current way to align the legend to the plot in the same way as the title. You can either left-align to the panel, which leaves a gap that looks weird compared to the nicely aligned title/subtitle:

diamonds |> 
  dplyr::count(cut, color) |> 
  ggplot(aes(n, cut, fill = color)) + 
  geom_col(position = "fill") + 
  labs(title = "Diamonds by Color and Cut",
       subtitle = "An example chart",
       fill = NULL, y = NULL, x = NULL) + 
  guides(fill = guide_legend(reverse = TRUE, nrow = 1)) + 
  ggthemes::theme_hc() + 
  theme(plot.title.position = "plot",
        legend.direction = "horizontal",
        legend.position = "top",
        legend.justification = "left")

image

Or you can create manual space in the subtitle and tweak the position of the legend just right to get it into place:

diamonds |> 
  dplyr::count(cut, color) |> 
  ggplot(aes(n, cut, fill = color)) + 
  geom_col(position = "fill") + 
  labs(title = "Diamonds by Color and Cut",
       subtitle = "An example chart\n\n",
       fill = NULL, y = NULL, x = NULL) + 
  guides(fill = guide_legend(reverse = TRUE, nrow = 1)) + 
  ggthemes::theme_hc() + 
  theme(plot.title.position = "plot",
        legend.direction = "horizontal",
        legend.position = c(-0.18, 1.1),
        legend.justification = "left")

image

The second option achieves the look I want, but it requires trial-and-error to get the right numbers for legend.position, and any change to the size of the output messes up the alignment.

I would like to be able to specify a plot.legend.position similar to plot.title.position that would align the legend to the plot instead of the panel:

theme(plot.title.position = "plot",
      plot.legend.position = "plot",
      legend.direction = "horizontal",
      legend.position = "top",
      legend.justification = "left")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions