0

I have a bar plot that has one very long legend element. I tried to use str_wrap but it didn't work. My x is not the issue, but rather the fill values. Can someone help me? How can I adapt the str_wrap to a plot using the fill aesthetics?

Some example data:

sex <- c(1, 1, 3, 1, 2, 2, 4, 1, 2, 2, 1, 1)
profession <- c("a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d", "d")
df <- data.frame(sex, profession)

My code:

ggplot(dat_sexpermedia_journalist,
       mapping = aes(x = profession, fill = sex)) +
  geom_bar() +
  scale_fill_brewer(palette = "Greens") +
  labs(x = "professions",
       y = "count", fill = "sex") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom")

Issue seen in x-axis

stefan
  • 90,330
  • 6
  • 25
  • 51
  • 3
    Try with `scale_fill_brewer(..., labels = scales::label_wrap(10))` – stefan Jun 25 '21 at 16:47
  • It would help to provide a [good reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – AndrewGB Jun 27 '21 at 04:59
  • Thank you @stefan! That worked right away. Is there a possibility in the scale_fill_brewer to align the labels on top/bottom? As for @AndyBrown: Thank you for the advice. I'm still very new to this. I will add a data frame that makes the example easily reproducible. – Kathrin Jun 28 '21 at 08:26

1 Answers1

0

As I mentioned in the comments you could wrap the legend labels via scale_fill_brewer(..., labels = scales::label_wrap(10)). The alignment of the labels could be set via the guide argument of the scale, e.g. guide = guide_legend(label.vjust = 1) will align the labels at the top, while 0 will align at the bottom. Moreover, I added an override.aes = list(size = 0)). The reason is that by default a (white) border line is drawn around the legend keys so that the labels do not align perfectly with the keys. To remove the border line I set its size to zero.

library(ggplot2)

sex <- c(1, 1, 3, 1, 2, 2, 4, 1, 2, 2, 1, 1) 
profession <- c("a", "a", "a", "b", "b", "b", "c", "c", "c", rep(paste(rep("World", 5), collapse = ", "), 3))
df <- data.frame(sex, profession)

ggplot(df, mapping = aes(x = sex, fill = profession)) +
  geom_bar() +
  scale_fill_brewer(palette = "Greens", labels = scales::label_wrap(20), 
                    guide = guide_legend(label.vjust = 1, override.aes = list(size = 0))) +
  labs(x = "Medienformen",
       y = "Anzahl", fill = "Geschlecht") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom")

stefan
  • 90,330
  • 6
  • 25
  • 51