Matheus Pacheco
Matheus Pacheco

Reputation: 1

How reduce space between shapes in ggplot legend?

I try reduce space between circles shape in a legend. How i do that? I want to leave the circles almost 'glued'.

For example:

pd = ggplot(iris, aes(Sepal.Length,
                      Sepal.Width))
head(iris$Species)

scale_pd = pd + geom_point(aes(fill = Species), pch = 21, 
                           alpha = 0.6,
                           size = 4)+ 
  labs(title="Iris dispersion",
       subtitle="Sepal length x Sepal Width per species",
       caption="",
       x="Sepal Width (cm)",
       y = "Sepal length (cm)") +
  theme_classic() +
  scale_fill_manual(name="Specie",
                    labels=c("Setosa","Versicolor","Virginica"),
                    values=c("#023047","#ffb703","#ef476f"))

I tried used

guide_legend(override.aes = list(shape = c(22, 22, 22),
                                                 size = 10), keyheight = .1)

but does't work

Upvotes: 0

Views: 62

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 173928

You can set legend.key.height to 0 in theme

ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(fill = Species), pch = 21, alpha = 0.6, size = 4)+ 
  labs(title="Iris dispersion",
       subtitle="Sepal length x Sepal Width per species",
       x = "Sepal Width (cm)",
       y = "Sepal length (cm)") +
  theme_classic() +
  scale_fill_manual(values=c("#023047","#ffb703","#ef476f")) +
  theme(legend.key.height = unit(0, "mm"))

enter image description here

Upvotes: 2

TarJae
TarJae

Reputation: 78947

One way is to use guide_legend():

scale_pd + guides(fill=guide_legend(
  keywidth=0.01,
  keyheight=0.01,
  default.unit="inch")
)

enter image description here

Upvotes: 1

Related Questions