I want to add text (n) on each bar in a horizontal bar plot in ggplot environment, but keep getting error message, I wonder what will be correct way to do so?
Also, I tried to invoke viridis package to add color on those bars but can't seem to get around. Is there any way to map different colors to those bars?
My current code is shown at below.
# the data
city_r <- data.frame(
City = c("A", "B", "C", "D", "E", "F"),
rating = c(5.52, 8, 6.24, 5.89, 5.57, 8.67),
n = c(112, 1, 25, 40, 9, 36)
)
# rating means mayor's rating
# n means respondents' size in each city
library(ggplot2)
# plot it
g <- city_r %>%
group_by(City) %>%
arrange(rating) %>%
ggplot(., mapping = aes(x=reorder(City, rating), y =rating))+
geom_text(aes(n), colour = "black", position = "dodge") +
geom_bar(stat = "identity", width=.8, position = position_dodge(width = .25))+
labs(
title = "",
y = "Mayor's rating",
x = ""
)+
coord_flip()
g

