Reputation: 77
I have a barplot (stat=identity) and would like to label the bars with N (the number of values of every bar). I have a problem with positive and negative bars. One resolution could be to make the labels of the positive bars in white oder to write them at the top.
ggplot(AP_Group, aes(Labels, Mean))+
geom_bar(stat = "identity") +
theme_minimal() +
ggtitle(expression(paste("Air Pressure - C_PM"[1], " - All Season"))) +
xlab("Air Pressure [hPa]") +
ylab("Shap Value") +
geom_text(aes(label=N), color="black", size=3.5, vjust = 1.8) +
theme(plot.title = element_text(color="black", size=14, margin = margin(t = 0, r = 0, b = 15, l = 0)),
axis.title.x = element_text(color="black", size=14, margin = margin(t = 15, r = 0, b = 0, l = 0)),
axis.title.y = element_text(color="black", size=14, margin = margin(t = 0, r = 15, b = 0, l = 0))) +
theme(plot.title = element_text(hjust=0.5))
Upvotes: 1
Views: 1075
Reputation: 9505
If you really want to color them conditionally to the sign, here a possible solution:
# fake df
df <- data.frame(Mean = c(1,3,-5),Labels = c("a","b","c"))
# here you decide to put white or black conditionally
df$color <- ifelse(df$Mean > 0, 'white','black')
library(ggplot2)
ggplot(df, aes(Labels, Mean))+
geom_bar(stat = "identity") +
theme_minimal() +
ggtitle(expression(paste("Air Pressure - C_PM", " - All Season"))) +
xlab("Air Pressure [hPa]") +
ylab("Shap Value") +
# here in aes() you put the color made
geom_text(aes(label=Mean, color=color), size=3.5, vjust = 1.8) +
# here you define the colors (it means "white" could be the color you want)
scale_color_manual(values = c("black" = "black", "white" = "white"))+
# you can remove the useless legend
theme(legend.position="none")
Upvotes: 1
Reputation: 18425
One way of doing it would to make vjust
an aesthetic like this...
df <- tibble(x = c(1, 2), y = c(-1, 2)) #sample data
df %>% ggplot(aes(x=x, y=y)) +
geom_bar(stat = "identity") +
geom_text(aes(label = y, vjust = -sign(y)))
Upvotes: 5