gpt4 book ai didi

r - 如何将图例框一直移动到图的左侧并与 ggplot2 中的标题和副标题对齐?

转载 作者:行者123 更新时间:2023-12-03 23:46:35 25 4
gpt4 key购买 nike

我有以下数据和图片设置如下

df <- data_frame(group = rep(c("A", "B"), each = 20),
y = c(sample(1:90, 20, replace = TRUE),
sample(1:30, 20, replace = TRUE)),
x = rep(1:20, 2)
)
ggplot(df, aes(x = x, y = y, color = group))+
geom_line()+
labs(x = "", y = "", title = "Comparison",
subtitle = "Unit (thousand)",
caption = "Source: Kaggle")+
theme(legend.title = element_blank(),
legend.position = "top",
legend.justification='left',
legend.box = "horizontal",
legend.key = element_blank(),
legend.box.margin = margin(0,0,0,0,"cm"),
plot.title.position = "plot",
plot.caption.position = "plot",
plot.caption = element_text(hjust = 0))

并在此处生成图表:

enter image description here

如何将图例框一直移动到情节的左侧并与标题和副标题对齐?还必须考虑到legend.key 中有一个边距。

如果您也可以让我知道如何减少图例周围的空间,也将不胜感激。谢谢!

最佳答案

这是指定 legend.position 的方法手动,以及添加 \n到副标题以创造额外的空间。您还需要 legend.direction = "horizontal"legend.margin = margin(0) :

请注意,您可能不得不摆弄 legend.position 中的数字。因为每个绘图设备都会略有不同。

ggplot(df, aes(x = x, y = y, color = group))+
geom_line()+
labs(x = "", y = "", title = "Comparison",
subtitle = "Unit (thousand)\n",
caption = "Source: Kaggle")+
theme(legend.title = element_blank(),
legend.position = c(-0.065,1.05),
legend.justification='left',
legend.box = "horizontal",
legend.margin = margin(0),
legend.key = element_blank(),
legend.direction = "horizontal",
plot.title.position = "plot",
plot.caption.position = "plot",
plot.caption = element_text(hjust = 0))

enter image description here

关于r - 如何将图例框一直移动到图的左侧并与 ggplot2 中的标题和副标题对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62363126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com