用正条和负条按值的数量标记条形图

Label a barplot by number of values with positive and negative bars

我有一个条形图 (stat=identity) 并想用 N(每个条形的值的数量)标记条形图。我对正条和负条有疑问。一种解决方案可能是将正条的标签制作成白色,或者将它们写在顶部。

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

一种方法是使 vjust 成为这样的美学...

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

如果你真的想有条件地将它们着色为标志,这里有一个可能的解决方案:

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