Skip to content

Feature request - Align horizontal legend width and plotting area #4896

@pachadotdev

Description

@pachadotdev

I need to align a horizontal legend with the square defined by the x and y-axis, as in the following example. This is partially related to #3989.

library(patchwork); library(dplyr)

g <- ggplot(mtcars, aes(mpg, wt, color = as.factor(am)))+
  geom_point()+
  guides(color = "none")

l <- ggplot(mtcars %>% distinct(am), 
            aes(as.factor(am), 1,  label = am)) +
  geom_point(aes(color = as.factor(am))) +
  geom_text(hjust = -1) +
  guides(color = "none") +
  theme(axis.text = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank(),
        axis.ticks = element_blank())

l + g + plot_layout(heights = c(1,20))

image

My idea is to be able to do this for any plot, ideally with pure ggplot2, and that the legend width is preserved when I use ggsave(). In addition, I've used different options inside theme() with the idea of doing this by using NPC

library(ggplot2)

g <- ggplot(mtcars) +
  geom_col(aes(x = cyl, y = mpg, fill = as.factor(am))) +
  theme(
    legend.position = "top",
    legend.justification = "center",
    legend.background = element_rect(fill = c("#f2f0f2"), colour = NA),
    legend.margin = margin(t = 0, r = 1, b = 0, l = 0, unit = "npc"),
    complete = T
  ) +
  theme(plot.background = element_rect(fill = "white", colour = NA))

g

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions