Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space between gpplot2 horizontal legend elements

Tags:

r

ggplot2

I have a ggplot2 plot as follows:

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), fill=factor(cyl))) + 
    geom_bar() +
    coord_flip() +
    theme(legend.position = 'top') +
    guides(fill = guide_legend(title=NULL))

I'd like add spacing between the fill elements as follows:

enter image description here

like image 422
Tyler Rinker Avatar asked Jul 15 '16 17:07

Tyler Rinker


People also ask

How to add more space between legend items in ggplot2?

Let’s continue… If we want to add additional white space between our legend items, we can use the legend.spacing.x argument within the theme function. Consider the following R programming code: Figure 2: ggplot2 Plot with Increased Spacing Between Legend Items. Compare Figure 1 with Figure 2.

How to create horizontal legend using Ggplot2 in R?

How to create horizontal legend using ggplot2 in R? How to create horizontal legend using ggplot2 in R? The default legend direction is vertical but it can be changed to horizontal as well and for this purpose we can use legend.direction argument of theme function of ggplot2 package.

How do I add spacing between entries in a legend?

To add spacing between entries in a legend, adjust the margins of the theme element legend.text. To add 30pt of space to the right of each legend label (may be useful for a horizontal legend): To add 30pt of space to the left of each legend label (may be useful for a vertical legend):

How to add additional white space between legend items in R?

Let’s continue… If we want to add additional white space between our legend items, we can use the legend.spacing.x argument within the theme function. Consider the following R programming code:


1 Answers

The issue mentioned by alistaire and Tyler Rinker was solved. Now we can adjust the margins of the element_text`.

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) +
  geom_bar() +
  coord_flip() +
  theme(
    legend.position = 'top',
    legend.title = element_blank(),
    legend.text = element_text(margin = margin(r = 2, unit = 'cm'))
  )

enter image description here

like image 105
mpalanco Avatar answered Nov 15 '22 21:11

mpalanco