1
votes

I want to customize different sizes for the labels inside a stacked barchart using ggplot2.

For example, a size 4 in the green bar, a size 3 in the light green, a size 2 in the yellow and so on. Below there is a link with an image of the plot. I cant figure out how to do it.

This is the code

ggplot(data, aes(x = as.factor(id), y=value, fill = cat, label = value)) +
  geom_bar(stat = "identity", alpha=0.5) +
  geom_text(size = 2.5, position = position_stack(vjust = 0.7)) +
  scale_fill_manual(values=c("#1E8E6B", "#6FBC84", "#FEEF51", "#EF6541", "#E81329"))

I want for example

enter image description here

1
Could you not simply do an aes(size = cat) combined with a scale_size_manual()? - teunbrand

1 Answers

0
votes

As @teunbrand mentioned, put your size= into aes() so that ggplot2 uses that as an aesthetic mapped to cat, and then use scale_size_manual() to set the sizes just like you already have done with the fill=.

ggplot(data, aes(x = as.factor(id), y=value, fill = cat, label = value)) +
  geom_bar(stat = "identity", alpha=0.5) +
  geom_text(aes(size = cat), position = position_stack(vjust = 0.7)) +
  scale_fill_manual(values=c("#1E8E6B", "#6FBC84", "#FEEF51", "#EF6541", "#E81329")) +
  scale_size_manual(values=c(4,3,2.5,2,1.5))

You can change the sizes however you wish or set values with a seq() function.