Avoid applying alpha aesthetics to geom_text in ggplot2

I have the following diagram ggplot2

. I don't want transparency on 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've tried moving alpha = round

as an aesthetic geom_bar()

, but then I lose the trick over labels:

without dodge

How can I reproduce the top diagram but not apply the transparency aesthetic to my labels?

+3


source to share


1 answer


I would move aes(alpha=)

to geom_bar

and then add aes(group=)

to geom_text

to restore the evasion.

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

This is a beautiful plot.

+4


source







All Articles