Home > Blockchain >  geom_text different color labels
geom_text different color labels

Time:02-11

I'm working with a categorical dataset of averages, modeled off of the following code:

iris %>%
  group_by(Species) %>%
  summarise(
    avg_sepal_width = mean(Sepal.Width),
    avg_sepal_length = mean(Sepal.Length)
  ) %>%
  pivot_longer(cols = c(avg_sepal_width, avg_sepal_length)) -> iris_avg

This provides me with the table:

Species name value
setosa avg_sepal_width 3.428
setosa avg_sepal_length 5.006
versicolor avg_sepal_width 2.770
versicolor avg_sepal_length 5.936
virginica avg_sepal_width 2.974
virginica avg_sepal_length 6.588

Working with this data, I cam creating a simple side-by-side bar chart using ggplot, as follows:

iris_avg %>%
  ggplot(aes(x = Species, y = value, fill = name))   
  geom_col(position = "dodge")   
  geom_text(aes(label = value), position = position_dodge(.9), vjust = 2)

I am trying to determine if there is a way for me to add a color = parameter in the geom_text layer that would allow me to make the two different categories (length and width) different colors.

CodePudding user response:

Add color=name to the text's aes(.). If you do that by itself, it'll choose the same colors as used for fill= above it, rendering the text the same color as the bar on which they are placed; to fix that, use scale_color_manual(values=..) to specify the colors in a named-vector.

iris_avg %>%
  ggplot(aes(x = Species, y = value, fill = name))   
  geom_col(position = "dodge")   
  geom_text(aes(label = value, color = name), position = position_dodge(.9), vjust = 2)  
  scale_color_manual(values = c(avg_sepal_length="green", avg_sepal_width="black"))

enter image description here

(Though perhaps you can find colors that don't look at ghastly.)

  • Related