ggplot中使用facet_wrap生成分面图后如何修改图例默认标题
问题原因
你当前的图例由aes()中的fill = Depth_bins映射生成,你调用scale_color_discrete修改的是color映射对应的图例,二者相互独立,所以修改不生效,该问题和facet_wrap没有关联。
可行解决方法
方法1:通过labs()直接指定(最简便)
直接在现有labs()参数中添加fill字段,定义fill映射的图例标题,修改后代码如下:
facet_8 <- ggplot(am_dives, aes(x = st_hr, fill = Depth_bins)) + geom_density(aes(y = ..count../sum(..count..)), position = "stack", alpha = 0.7) + scale_x_datetime(date_labels = "%H:%M") + labs(x = "Start hour", y = "Density", fill = "Depth Bins") + # 新增fill参数定义图例标题 facet_wrap(~ID, dir = "v", scales = "free_y") facet_8
方法2:修改fill对应的scale参数
把你原本写的scale_color_discrete替换为对应fill映射的scale即可:
facet_8 <- ggplot(am_dives, aes(x = st_hr, fill = Depth_bins)) + geom_density(aes(y = ..count../sum(..count..)), position = "stack", alpha = 0.7) + scale_x_datetime(date_labels = "%H:%M") + labs(x = "Start hour", y = "Density") + facet_wrap(~ID, dir = "v", scales = "free_y") + scale_fill_discrete(name = "Depth Bins") # 替换为fill对应的scale修改标题 facet_8
方法3:自定义配色时同步修改标题
如果你后续需要自定义深度分箱的颜色、展示标签,也可以在自定义fill scale时同步设置标题,示例如下:
facet_8 <- ggplot(am_dives, aes(x = st_hr, fill = Depth_bins)) + geom_density(aes(y = ..count../sum(..count..)), position = "stack", alpha = 0.7) + scale_x_datetime(date_labels = "%H:%M") + labs(x = "Start hour", y = "Density") + facet_wrap(~ID, dir = "v", scales = "free_y") + scale_fill_manual( name = "Depth Bins", # 图例标题 values = c("#1f77b4", "#ff7f0e", "#2ca02c"), # 自定义颜色,数量和深度分箱数量匹配即可 labels = c("0-10m", "10-30m", ">30m") # 可选:自定义图例展示标签 ) facet_8
内容的提问来源于stack exchange,提问作者R student
相关产品推荐
相关产品推荐

