ggplot2中的多个geom_text语句重叠标签

时间:2019-08-07 15:06:36

标签: r ggplot2 geom-text

我正在制作带有误差线的ggplot,即使我在geom_text函数中使用check_overlap = T,它们中的一个还是有重叠文本

最后一家医院主要是个问题

ggplot(scores, aes(x=hospital, y=mean), xlab = "score") + 
  geom_point(shape = 19, size = 3) + 
  #geom_line(color="blue") + 
  geom_errorbar(aes(x=hospital, ymin=lower, ymax=upper), color="blue", width=.5) + 
  coord_flip() + 
  theme(axis.text=element_text(size=20), axis.title=element_text(size=25,face="bold"), 
        plot.title = element_text(face = "bold", size = 30)) + 
  ggtitle("Linear Regression Predictions for Scores") + ylab("Score")+ xlab("Hospital") + 
  labs(subtitle = "Data used for Prediction: 2014-2019") + 
  geom_text(aes(label = round(mean, 1)),vjust = -1, size = 8, check_overlap = T)+ 
  geom_text(aes(y = lower, label = round(lower, 1)),vjust= -1, size = 8, check_overlap = T) + 
  geom_text(aes(y = upper, label = round(upper, 1)),vjust = -1, size = 8, check_overlap = T) 

Dataframe:      
        hospital      mean    lower     upper
1       A             50      40        60
2       B             60      55        65
3       C             80      78        82
4       D             70      65        75
5       E             99      98        100

1 个答案:

答案 0 :(得分:1)

我建议为文本使用较长版本的数据,以便您一次调用geom_text就可以得到它:

library(dplyr); library(tidyr); library(ggplot2)
scores_long <- hospital %>%
  gather(stat, value, -hospital) %>%
  mutate(value = round(value, 1))

ggplot(data = scores, aes(x=hospital, y=mean), xlab = "score") + 
  geom_errorbar(aes(x=hospital, ymin=lower, ymax=upper), color="blue", width=.5) + 
  geom_point(shape = 19, size = 3) + 
  coord_flip() + 
  theme(axis.text=element_text(size=20), axis.title=element_text(size=25,face="bold"), 
        plot.title = element_text(face = "bold", size = 30)) + 
  ggtitle("Linear Regression Predictions for Scores") + ylab("Score")+ xlab("Hospital") + 
  labs(subtitle = "Data used for Prediction: 2014-2019") +
  geom_text(data = scores_long, 
            aes(label = value, y = value), vjust = -1, size = 8, check_overlap = T)

enter image description here