如何在R ggplot2中添加独立于原始数据集的自定义图例?
在ggplot2中添加完全自定义的独立图例
当然可以添加完全脱离原始数据集的自定义图例,下面给你两种实用的实现方法:
方法一:用ggnewscale创建风格统一的独立图例
如果想要和现有图例风格保持一致的独立图例,推荐用ggnewscale包,它能帮你添加新的美学刻度,实现多个同类型的独立图例:
首先安装并加载依赖包:
install.packages("ggnewscale") library(ggplot2) library(ggnewscale) set.seed(123) # 固定随机数,让结果可复现
修改你的代码实现需求:
df <- data.frame( x = 1:5, y = rnorm(5), z = c('a', 'b', 'c' , 'd' , 'e') ) ggplot(df, aes(x = x, y = y, fill = z)) + geom_point(shape = 21, size = 3) + # 用shape=21才能显示填充色 # 开启新的fill刻度,和原始fill图例分开 new_scale_fill() + # 添加一个不在绘图范围内的虚拟点(x=-Inf,y=-Inf不会显示在图上) geom_point(aes(fill = "custom"), x = -Inf, y = -Inf, shape = 21, size = 3) + # 定义自定义图例的样式和文字 scale_fill_manual( name = NULL, # 去掉图例标题,需要的话可改成自定义文字 values = "red", labels = "ABCDE" )
方法二:手动绘制自定义图例作为注释
如果需要更自由地控制图例的位置和样式(比如放在图表任意角落),可以用grid包手动绘制图例元素,再用annotation_custom添加到图表:
library(ggplot2) library(grid) set.seed(123) df <- data.frame( x = 1:5, y = rnorm(5), z = c('a', 'b', 'c' , 'd' , 'e') ) # 绘制基础图表 p <- ggplot(df, aes(x = x, y = y, fill = z)) + geom_point(shape = 21, size = 3) # 创建自定义图例的图形元素 custom_legend <- grobTree( # 红色填充圆形 circleGrob(x = 0, y = 0.5, r = 0.1, gp = gpar(fill = "red", col = "black")), # 图例文字 textGrob("ABCDE", x = 0.2, y = 0.5, hjust = 0, size = 10), # 可选:给图例加边框 rectGrob(x = 0, y = 0, width = 0.8, height = 1, just = c("left", "bottom"), gp = gpar(fill = NA, col = "black")) ) # 添加到图表右上角(可调整xmin/xmax/ymin/ymax改变位置) p + annotation_custom( custom_legend, xmin = 5.2, xmax = 6, ymin = max(df$y) + 0.2, ymax = max(df$y) + 0.8 )
注意:原始代码里的geom_point默认shape是19(实心圆),没有填充属性,要改成shape=21-25这类带填充的形状,才能显示fill映射的颜色。
内容的提问来源于stack exchange,提问作者Peter Yoo
相关产品推荐
相关产品推荐

