R语言 如何对齐左上角的标题和图例

k97glaaz  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(306)
ggplot(mtcars, aes(wt, qsec)) + 
  geom_point(
    aes(
       size = mpg
  )) + 
  labs(x = "", y = "", title = 'This is title', subtitle = 'This is subtitle') +
  guides(size = guide_legend(nrow = 1)) + 
  theme(
    panel.border = element_blank(),
    legend.position = 'top',
    legend.justification = 'left',
    plot.title = element_text(size = 18),
  )

我将标题和图例都设置为左上角,但它们显示左上角的方式似乎不同。感觉标题位于整个图像的左上角,但图例位于绘图区域的左上角,因此它们没有水平对齐

后来我在themes()中定义了legend.position,但这会使绘图区域变得模糊,看起来不太好

ggplot(mtcars, aes(wt, qsec)) + 
  geom_point(
    aes(
       size = mpg
  )) + 
  labs(x = "", y = "", title = 'This is title', subtitle = 'This is subtitle') +
  guides(size = guide_legend(nrow = 1)) + 
  theme(
    panel.border = element_blank(),
    legend.position = c(-0.01,0.9),
    legend.justification = 'left',
    plot.title = element_text(size = 18),
  )

我希望你能帮我

dfddblmv

dfddblmv1#

您可以将legend.margin设置为具有负的左侧边距。

library(tidyverse)

ggplot(mtcars, aes(wt, qsec)) + 
  geom_point(
    aes(
      size = mpg
    )) + 
  labs(x = "", y = "", title = 'This is title', subtitle = 'This is subtitle') +
  guides(size = guide_legend(nrow = 1)) + 
  theme(
    panel.border = element_blank(),
    legend.position = 'top',
    legend.justification = 'left',
    legend.margin = margin(c(0, -1, 0, 0)),
    plot.title = element_text(size = 18),
  )

创建于2023年3月3日,使用reprex v2.0.2

相关问题