R ggplot:在geom_bar中使用geom_text或geom_label

问题描述 投票:0回答:1

我正在计划在时间表上发表关于特定研究主题的科学论文。我想使用“标签”变量将作者和年份添加到相应的矩形中。

条形图

但是,geom_text() 或 geom_label() 要求提供 y 美学,而我不需要使用 geom_bar() 。有解决办法吗?

这是我的代码(可重现的示例):

year <- c(2012, 2023, 2020, 2023,
          2019, 2017, 2022, 2022,
          2018, 2021, 2016, 2017,
          2019, 2020, 2019, 2022,
          2016, 2021, 2020, 2022,
          2022, 2020, 2015, 2021,
          2021, 2024, 2023)

label <- c('Henry et al. (2012)', 'Breitmayer et al. (2023)', 'Deutsch & Piccirillo (2020)', 'Engelke et al. (2023)',
           'Gerull et al. (2019)', 'Goldberg et al. (2017)', 'Kraft et al. (2022)', 'Lourenco et al. (2022)',
           'Muniandi et al. (2018)', 'Prakash et al. (2021)', 'Probst et al. (2016)', 'Probst et al. (2017)', 
           'Pryss et al. (2019)', 'Pryss et al. (2020)', 'Pryss et al. (2019)', 'Schlee et al. (2022)', 
           'Schlee et al. (2016)', 'Schlee, Simoes & Pryss (2021)', 'Schleicher et al. (2020)', 'Shahania et al. (2022)', 
           'Simoes et al. (2022)', 'Unnikrishnan et al. (2020)', 'Wilson et al. (2015)', 'Lourenco et al. (2021)', 
           'Dode et al. (2021)', 'Engelke et al. (2024)', 'Kleinau et al. (2023)')

topic <- c('feasibility', 'ML', 'review', 'outcome',
           'feasibility', 'feasibility', 'software', 'feasibility',
           'ML', 'ML', 'symptom interaction', 'symptom interaction', 
           'retrospective comparison', 'ML', 'software', 'feasibility', 
           'feasibility', 'outcome', 'ML', 'ML', 
           'symptom interaction', 'ML', 'feasibility', 'feasibility', 
           'retrospective comparison', 'outcome', 'ML')

df_hist <- data.frame(year, label, topic)

ggplot(df_hist, aes(year, fill = topic, group = topic)) +
  geom_bar() +
  scale_fill_manual(values=c("#F09EA7", "#F6CA94", "#FAFABE", "#C1EBC0", "#C7CAFF", "#CDABEB", "#F6C2F3")) +
  theme_bw()
r ggplot2 geom-bar geom-text
1个回答
0
投票

您可以将 stat_count 与文本几何对象一起使用:

ggplot(df_hist, aes(x = year)) +
  geom_bar(aes(fill = topic, group = topic)) +
  scale_fill_manual(values=c("#F09EA7", "#F6CA94", "#FAFABE", "#C1EBC0", "#C7CAFF", "#CDABEB", "#F6C2F3")) +
  stat_count(geom = "text", aes(label = label, x = year, group = label), angle = -90, size = 3, hjust = -0.1) +
  theme_bw()
© www.soinside.com 2019 - 2024. All rights reserved.