ggplot添加的文本标签无法显示问题求助
解决ggplot添加事件文本不显示的问题
问题根源
你设置的ymin = 250大概率超出了当前图表y轴的实际最大值,导致文本被放置在绘图区域之外;即便开启了coord_cartesian(clip = "off"),如果顶部没有预留足够边距,依然看不到文本。另外annotation_custom对于按年份标注的场景,不如geom_text灵活可控。
方案一:调整annotation_custom参数与图表边距
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") + # 动态获取y轴最大值,将文本放在最大值上方 annotation_custom(grid::textGrob("event 1", rot = 90), xmin = 2010, xmax = 2010, ymin = max(S$AnnualProduction$Articles) + 10) + annotation_custom(grid::textGrob("event 2", rot = 90), xmin = 2011, xmax = 2011, ymin = max(S$AnnualProduction$Articles) + 10) + coord_cartesian(clip = "off") + theme_minimal() + # 增加顶部边距,让文本显示出来 theme(plot.margin = margin(t = 30, r = 10, b = 10, l = 10)) pub_over_year
方案二:用geom_text实现(推荐)
先创建事件数据框,直接通过geom_text绘制,无需依赖annotation_custom:
# 构建事件数据 events <- tibble( Year = c(2010, 2011), Event = c("event 1", "event 2"), # 将文本位置设为y轴最大值上方固定偏移量 y_pos = max(S$AnnualProduction$Articles) + 10 ) 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") + # 添加事件文本并旋转90度 geom_text(data = events, aes(x = Year, y = y_pos, label = Event), angle = 90, hjust = 0, size = 3) + coord_cartesian(clip = "off") + theme_minimal() + theme(plot.margin = margin(t = 30, r = 10, b = 10, l = 10)) pub_over_year
以上两种方式都能让事件文本显示在图表顶部对应年份的位置,且通过动态获取y轴最大值,可适配不同的数据范围,避免位置偏差。
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

