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

我有一个小节(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",margin = margin(t = 15,b = 0,axis.title.y = element_text(color="black",r = 15,l = 0))) +
  theme(plot.title = element_text(hjust=0.5))

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

coldboyjack 回答:用正数和负数条按值的数量标记条形图

一种实现方法是使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)))

enter image description here

,

如果您真的想有条件地为标志涂上颜色,则可以采用以下解决方法:

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

enter image description here

本文链接:https://www.f2er.com/3138301.html

大家都在问