ggplot中图例键之间的间距 [英] Spacing between legend keys in ggplot

查看:86
本文介绍了ggplot中图例键之间的间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在图的顶部有一个图例.我希望图例保持对齐,并能够设置(1)美学符号(彩色正方形)与文本之间的间距,以及(2)文本与下一个美学符号之间的间距.

 库(tidyverse)mtcars%>%mutate(transmission = ifelse(am,"manual","automatic"))%&%ggplot()+aes(x =传输,fill =传输)+geom_bar()+实验室(填充= NULL)+主题(#legend.spacing.x = unit(.5,"char"),#也在左侧增加间距legend.position =顶部",legend.justification = c(0,0),legend.title = element_blank(),legend.margin = margin(c(5,5,5,0))) 

解决方案

I have a legend on the top of the graph. I want the legend to be left aligned and to be able to set the spacing (1) between the aesthetic symbol (colored square) and the text and (2) between the text and the next aesthetic symbol.

library(tidyverse)

mtcars %>% 
  mutate(transmission = ifelse(am, "manual", "automatic")) %>% 
ggplot() +
  aes(x = transmission, fill = transmission) +
  geom_bar() +
  labs(fill = NULL) +
  theme(
    #legend.spacing.x = unit(.5, "char"), # adds spacing to the left too
    legend.position = "top", 
    legend.justification = c(0,0),
    legend.title=element_blank(),
    legend.margin=margin(c(5,5,5,0)))

解决方案

Adding a margin to adjust element_text

mtcars %>%
  mutate(transmission = ifelse(am, "manual", "automatic")) %>%
  ggplot() +
  aes(x = transmission, fill = transmission) +
  geom_bar() +
  labs(fill = NULL) +
  theme(
    #legend.spacing.x = unit(.5, "char"), # adds spacing to the left too
    legend.position = "top",
    legend.justification = c(0, 0),
    legend.title = element_blank(),
    legend.margin = margin(c(5, 5, 5, 0)),
    legend.text = element_text(margin = margin(r = 10, unit = "pt")))

这篇关于ggplot中图例键之间的间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆