ggplot中theme_classic()致图例位置失效,如何固定图例在底部?
解决ggplot中theme_classic()覆盖图例位置的问题
问题出在主题设置的执行顺序:ggplot的主题配置遵循「后执行语句覆盖先执行」的规则。你先设置了theme(legend.position="bottom"),之后调用theme_classic()会重置所有主题默认参数(包括将图例位置恢复为默认的右侧),导致之前的设置被覆盖失效。
只需调整代码顺序,把theme(legend.position="bottom")放在theme_classic()之后,就能在保留主题样式的同时,固定图例在底部:
#GENERAL ggplot(data_meta_general, aes(x = reorder(Nombre.del.anuncio, +Alcance), y = Alcance, fill = Entrega.del.anuncio)) + geom_col() + coord_flip() + theme_classic() + theme(legend.position="bottom") + # 移至theme_classic()之后生效 labs(x = "Contenidos", y = "Alcance", title = "Top contenidos General") + scale_y_continuous(labels = comma) + geom_text( aes(x = Nombre.del.anuncio, y = Alcance , label = scales::comma(Alcance)), hjust = 0.75, size = 3, inherit.aes = TRUE)
如果想要优化底部图例的显示效果(比如让图例水平排列),可以补充更多配置:
theme( legend.position="bottom", legend.direction="horizontal", # 图例水平排列适配底部 legend.title.align=0.5 # 图例标题居中 )
内容的提问来源于stack exchange,提问作者Jorge Luis Fernández
相关产品推荐
相关产品推荐

