简体   繁体   中英

geom_text different color labels

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.

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"))

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM