【问题标题】:How to label only once when plotting multiple longitudinal trajectories in R?在 R 中绘制多个纵向轨迹时如何只标记一次?
【发布时间】:2019-10-10 05:57:02
【问题描述】:

我已经完成了一个包含多个轨迹的绘图,就像图像中的那样 https://i0.wp.com/svbtleusercontent.com/xcexi7wk8xsj1w_small.png?w=456&ssl=1 让我们用它作为一个可重现的例子:

library(ourworldindata)
id <- financing_healthcare %>% 
     filter(continent %in% c("Oceania", "Europe") & between(year, 2001, 2005)) %>% 
     select(continent, country, year, health_exp_total) %>% 
     na.omit()
ggplot(id, aes(x = year, y = health_exp_total, group = country, color = continent)) +
     geom_line()

如果我想在我制作的图中添加国家/地区的标签

ggplot(id, aes(x = year, y = health_exp_total, group = country, color = continent, label= country)) +
     geom_line()+geom_text()

但因此,这些标签每年都会重复出现并与其他标签重叠。是不是每个标签只出现一年,避免重叠?

非常感谢!

【问题讨论】:

  • 为避免标签重叠,您可以使用ggrepel

标签: r ggplot2 plot label geom-text


【解决方案1】:
#devtools::install_github('drsimonj/ourworldindata')
library(ourworldindata)
library(dplyr)
library(ggplot2)
library(ggrepel)

id <- financing_healthcare %>% 
  filter(continent %in% c("Oceania", "Europe") & between(year, 2001, 2005)) %>% 
  select(continent, country, year, health_exp_total) %>% 
  na.omit()

idl = id %>% filter(year == 2005)
ggplot(id, aes(x = year, y = health_exp_total, group = country, color = continent)) +
  geom_line() +
  geom_text_repel(data=idl, aes(label=country), size=2.5)

enter image description here

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2013-04-09
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多