在图的右上角的框中显示标签

问题描述

如下图所示,状态名称有时离该行很远。要考虑的一种选择是不将标签放在线条旁边,而是将它们包括在图的右上角的框中。我该怎么办?

这是我认为需要修改的部分代码

    geom_line(aes(x =Year,y = Age.Adjusted.Rate,colour = State),data = d_filtered_top5_fe)+
  
  ggrepel::geom_text_repel(aes(x =Year,colour = State,label = State,fontface = 'bold'),data = d_filtered_top5_fe %>% 
                             
                             filter(Year == max(Year)),segment.color = 'transparent',size = 2.5
  ) +

enter image description here

解决方法

没有您的数据,很难找到确切的解决方案。我猜可能有几种方法可以解决此问题。最简单的一种是使用图例。我们可以尝试这样的事情:

library(ggplot2)
ggplot(data = mtcars)+
geom_line(aes(x =wt,y = mpg,colour = factor(cyl))) + 
  theme( legend.position = c(0.9,.9),) +
  facet_wrap(vars(am))

如果您可以提供可复制的示例,它将帮助其他人帮助您。

enter image description here