'R: ggplot2 geom_text by condition (for selected)
I need to copy this bar chart

The problem is that I don't know how to make red and blue labels on the bars and save grey for others. According to the task red labels should highlight whether the character is included in Golden Trio (Harry, Hermione Granger, Ron Weasley). So their bars should contain this red label and others characters should have grey labels.
My code is here:
ggplot(data = actions, aes(x = names_ordered, y = tot)) + geom_bar(stat = "identity",color="grey85", fill="grey90") +
labs(title = "Character aggression \nHarry Potter Universe", caption = "pmsar2020_hw1_shivarova") + theme_classic() +
geom_text(aes(label = tot), size = 3, vjust = 2, colour = "grey30") + theme(plot.title = element_text(hjust = 0.5),
plot.caption.position = "plot",
plot.caption = element_text(hjust = 1,
face = "italic",
color = 'grey60'),
axis.title.x=element_blank(),
axis.title.y =element_blank())
Solution 1:[1]
One option would be to add a column to your dataset with the desired color for each category. For the assignment you could e.g. use dplyr::case_when. Afterwards you could map this new column on the color aes and use scale_color_identity:
Using some fake data to mimic your real dataset:
actions <- data.frame(
names_ordered = LETTERS[1:8],
tot = 8:1
)
library(ggplot2)
library(dplyr)
actions$color <- dplyr::case_when(
actions$names_ordered %in% c("A", "C", "D") ~ "darkred",
actions$names_ordered %in% c("E") ~ "blue",
TRUE ~ "grey30"
)
ggplot(data = actions, aes(x = names_ordered, y = tot)) +
geom_bar(stat = "identity", color = "grey85", fill = "grey90") +
labs(title = "Character aggression \nHarry Potter Universe", caption = "pmsar2020_hw1_shivarova") +
theme_classic() +
geom_text(aes(label = tot, color = color), size = 3, vjust = 2) +
scale_color_identity() +
theme(
plot.title = element_text(hjust = 0.5),
plot.caption.position = "plot",
plot.caption = element_text(
hjust = 1,
face = "italic",
color = "grey60"
),
axis.title.x = element_blank(),
axis.title.y = element_blank()
)

Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stefan |
