ggplot图例背景透明度设置及自定义排序问题求助
解决ggplot+ggnewscale的两个图例问题:背景透明与自定义排序
一、图例背景透明不生效的解决方法
你用legend.box.background设置背景透明没效果,是因为ggnewscale创建的是独立的图例对象,而legend.box.background仅控制整个图例组的外层容器样式。要给每个图例单独添加带透明度的背景,需要在每个scale_fill_manual里通过guide参数指定单个图例的主题样式:
在scale_fill_manual中加入guide = guide_legend(theme = theme(legend.background = element_rect(fill = alpha('#e5e5e5', 0.60), size = 0.1, color = '#333333'))),就能给每个图例单独设置带透明度的背景边框。
二、自定义图例顺序(把1、2改成2、1)
默认图例顺序是按你添加scale的先后排列的,要反转顺序,只需要给每个scale设置order参数:
- 把名称为"1"的scale的
order设为2(让它排后面) - 把名称为"2"的scale的
order设为1(让它排前面)
修改后的完整代码
library(ggplot2) library(ggnewscale) data = structure(list(grp1 = c("X", "X", "X", "X", "Y", "Y", "Y", "Y" ), grp2 = c("A", "B", "C", "D", "A", "B", "C", "D"), val = c(1, 2, 3, 4, 3, 4, 5, 6)), row.names = c(NA, -8L), class = "data.frame") col_define = c('red', 'orange', 'blue', 'lightblue') names(col_define) = c('A', 'B', 'C', 'D') ggplot(data, aes(x = grp1, group = grp2, y = val)) + geom_col(aes(fill = grp2)) + scale_fill_manual( values = col_define, breaks = c("A", "B"), name = "1", # 设置该图例顺序为2(靠后) order = 2, # 给单个图例加带透明度的背景 guide = guide_legend( theme = theme( legend.background = element_rect( fill = alpha('#e5e5e5', 0.60), size = 0.1, linetype = 'solid', color = '#333333' ) ) ) ) + new_scale_fill() + geom_col(aes(fill = grp2)) + scale_fill_manual( values = col_define, breaks = c("C", "D"), name = "2", # 设置该图例顺序为1(靠前) order = 1, # 给单个图例加带透明度的背景 guide = guide_legend( theme = theme( legend.background = element_rect( fill = alpha('#e5e5e5', 0.60), size = 0.1, linetype = 'solid', color = '#333333' ) ) ) ) + theme( legend.position="top", legend.direction = 'vertical', legend.box.margin = margin() # 原legend.box.background可删除,已给每个图例单独设置背景 )
补充说明
- 若想给整个图例组的外层也加背景,可保留
legend.box.background,但每个图例的独立背景仍需用上述方法设置。 order参数数值越小,图例排列越靠前,调整两个scale的order值即可自由定义顺序。
内容的提问来源于stack exchange,提问作者Bogaso
相关产品推荐
相关产品推荐

