使用ggplot2的facet_wrap()时如何为指定分面添加单独注释?
仅在指定分面添加注释的解决方案
要实现只在Fiction分面中添加注释,不能直接用annotate()(它会在所有分面渲染),可以通过**创建专属注释数据框+geom_text()**的方式实现,具体步骤如下:
先单独创建包含注释信息和对应分面标识的数据框:
annotation_df <- data.frame( Year = 2012, Rating = 3.37, label = "The Casual Vacancy by JK Rowling (3.3)", Genre = "Fiction" # 指定注释所属的分面 )在ggplot代码中替换原
annotate()部分,改用geom_text()并绑定注释数据框:ggplot(data=books_df_new)+ geom_jitter(mapping = aes(x=Year,y=Rating))+ facet_wrap(~Genre)+ geom_text( data = annotation_df, mapping = aes(x=Year, y=Rating, label=label), size=2.3, fontface="bold" )
原理说明
annotate()属于全局图层,不会识别分面变量;而geom_text()如果传入包含分面变量(Genre)的数据框,会自动匹配facet_wrap()的分面规则,只在Genre值为"Fiction"的分面中渲染注释文本。
内容的提问来源于stack exchange,提问作者Jordan Omar Roche
相关产品推荐
相关产品推荐

