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.
我在图表的顶部有一个图例。我希望图例左对齐,并能够在美学符号(彩色方块)和文本之间设置间距(1),在文本和下一个美学符号之间设置(2)。
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)))
1 个解决方案
#1
2
Adding a margin to adjust element_text
添加边距以调整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")))
#1
2
Adding a margin to adjust element_text
添加边距以调整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")))