添加到ggplot的文本标签不显示

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

下图显示了几年来的发表频率。我想在剧情的上半部分添加这些年来发生的事件。

我尝试了以下代码:

pub_over_year <- as_tibble(S$AnnualProduction) %>% 
  ggplot(aes(x = Year, y = Articles, group = 1)) +
  geom_point() +
  geom_line()+
  labs(x = "Years", y = "Number of publications") +
  geom_text(aes(label= Articles), hjust= 0.5, vjust = -2, size= 3, color= "black") +
  coord_cartesian(clip = "off") +
  theme_minimal()  +
  annotation_custom(grid::textGrob("event 1", rot = 90), 
                    xmin = 2010, xmax = 2010, ymin = 250) +
  annotation_custom(grid::textGrob("event 2", rot = 90), 
                    xmin = 2011, xmax = 2011, ymin = 250)
pub_over_year

我没有收到错误消息,但未显示文本标签。

r ggplot2
1个回答
0
投票

如果您可以包含您的数据(或其样本),那就更好了。使用一些虚构的数据,文本标签可以按原样与代码一起显示。它们是否超出了您的数据范围,例如将下面的

ymin
更改为
260
将丢失“事件 1”文本。

library(tibble)
library(ggplot2)

tibble(Year = 2009:2012, Articles = 248:251) %>%
  ggplot(aes(x = Year, y = Articles, group = 1)) +
  geom_point() +
  geom_line() +
  labs(x = "Years", y = "Number of publications") +
  geom_text(aes(label = Articles), hjust = 0.5, vjust = -2, size = 3, color = "black") +
  coord_cartesian(clip = "off") +
  theme_minimal() +
  annotation_custom(grid::textGrob("event 1", rot = 90),
    xmin = 2010, xmax = 2010, ymin = 250
  ) +
  annotation_custom(grid::textGrob("event 2", rot = 90),
    xmin = 2011, xmax = 2011, ymin = 250
  )

创建于 2024-04-24,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.