Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid applying alpha aesthetic to geom_text in ggplot2

Tags:

r

ggplot2

I have the following ggplot2 chart. I don't want transparency on the value labels.

ggplot2 chart

Code:

ggplot(test, aes(x = reorder(org, -as.numeric(level)), y = obsAvg, fill = level, alpha = round)) + 
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +
  scale_alpha_manual(values = c(.5, .75, 1), guide = FALSE) + 
  labs(title = "Average Observation Score by Round", y = "", x = "", fill = "Group") +
  theme_bw() +
  geom_text(aes(label = round(obsAvg,1)), vjust = -.5, size = 4, fontface="bold", position = position_dodge(width = .9)) +
  scale_y_continuous(limits = c(0,4), expand = c(0,0)) +
  theme(legend.position="bottom")

Data:

set.seed(1)
test <- data.frame(
  org = rep(c("Mammals", "Cats", "Tigers", "Lions", "Cheetahs"), 3),
  level = rep(c("Animals", "Family", rep("Species", 3)), 3),
  group = rep("Cats",15),
  round = rep(c("Round1", "Round2", "Round3"),5),
  obsAvg = runif(15, 1, 4)
)

I have tried moving the alpha = round to be an aesthetic of geom_bar() but then I lose the dodge of the labels:

without dodge

How can I replicate the top chart but not apply the transparency aesthetic to my labels?

like image 931
Sam Firke Avatar asked Dec 04 '25 10:12

Sam Firke


1 Answers

I would move the aes(alpha=) to geom_bar and then add an aes(group=) to geom_text to recover the dodging.

ggplot(test, aes(x = reorder(org, -as.numeric(level)), y = obsAvg, fill = level)) + 
  geom_bar(aes(alpha=round), stat = "identity", position = "dodge") +
  scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +
  scale_alpha_manual(values = c(.5, .75, 1), guide = FALSE) + 
  labs(title = "Average Observation Score by Round", y = "", x = "", fill = "Group") +
  theme_bw() +
  geom_text(aes(label = round(obsAvg,1), group=round), vjust = -.5, size = 4, fontface="bold", position = position_dodge(width = .9)) +
  scale_y_continuous(limits = c(0,4), expand = c(0,0)) +
  theme(legend.position="bottom")

enter image description here

That's a pretty plot.

like image 133
MrFlick Avatar answered Dec 07 '25 07:12

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!