I have a question about changing color for geom_text & geom_label base on a condition.
Expected out put
- Data label has
color = bluefor 2021,color = greyfor 2020 - Gap label is red when
negativeand green whenpositive
Data
data <- tibble(Factor = c("A", "B", "A", "B"),
Score = c(90, 85, 85, 90),
Year = c("2020", "2020", "2021", "2021"))
Data transform
df_2 = data %>%
pivot_wider(names_from = Year, names_prefix = "Year", values_from = Score) %>%
mutate(gap = Year2021 - Year2020) %>%
select(Factor, gap)
Plot
data %>%
left_join(df_2) %>%
ggplot(aes(x = Factor, y = Score, fill = Year)) +
geom_col(position='dodge') +
geom_text(aes(label=Score),
position=position_dodge(width = 0.9),
vjust=-0.40) +
geom_label(aes(y = 100, label = ifelse(Year == 2021, gap, NA_character_)), na.rm = TRUE) +
scale_y_continuous(limits = c(0,105))
theme_minimal()
Expected out put
85 & 90 = bluefor 2021,90 & 85 = greyfor 2020-5 = redand5 = green


