我创建了一个使用ggnewscale软件包创建的具有2个颜色比例和2个线型比例的打印。我希望图例显示在绘图的底部,图例标题显示在标签的上方。我半途而废,因为在我的尝试中,第一个音阶(来自geom_vline())没有以我想要的方式出现。在用new_scale()和new_scale_color().Does声明下一个比例之前,我甚至试图指出这个比例的理想位置,有人知道我如何解决这个问题吗?
library(ggplot2)
library(ggnewscale)
mtcars$cyl <- factor(mtcars$cyl)
# Attempt 1
ggplot(data = mtcars,
aes(x = wt,
y = mpg)) +
geom_vline(aes(xintercept = gear,
color = "Important line",
linetype = "Important line")) +
scale_linetype_manual(name = "Important lines",
values = 1) +
scale_color_manual(name = "Important lines",
values = "red") +
new_scale("linetype") +
new_scale_color() +
geom_line(aes(linetype = cyl,
color = cyl)) +
theme(legend.position = "bottom") +
guides(linetype = guide_legend(title.position = "top"),
color = guide_legend(title.position = "top"))
# Attempt 2
ggplot(data = mtcars,
aes(x = wt,
y = mpg)) +
geom_vline(aes(xintercept = gear,
color = "Important line",
linetype = "Important line")) +
scale_linetype_manual(name = "Important lines",
values = 1) +
scale_color_manual(name = "Important lines",
values = "red") +
guides(linetype = guide_legend(title.position = "top",
label.position = "bottom"), # Before new scales
color = guide_legend(title.position = "top",
label.position = "bottom")) +
new_scale("linetype") +
new_scale_color() +
geom_line(aes(linetype = cyl,
color = cyl)) +
theme(legend.position = "bottom") +
guides(linetype = guide_legend(title.position = "top"),
color = guide_legend(title.position = "top"))两次尝试都会产生相同的情节,这不是我想要的。

发布于 2021-07-21 19:19:22
不确定是否还有其他选择,但在使用ggnewscale时,对我起作用的是通过scale的guide参数设置指南的样式。为了实现这一点,我添加了一个´scale_color_discrete`:
library(ggplot2)
library(ggnewscale)
mtcars$cyl <- factor(mtcars$cyl)
ggplot(data = mtcars,
aes(x = wt,
y = mpg)) +
geom_vline(aes(xintercept = gear,
color = "Important line",
linetype = "Important line")) +
scale_linetype_manual(name = "Important lines",
values = 1, guide = guide_legend(title.position = "top") ) +
scale_color_manual(name = "Important lines",
values = "red", guide = guide_legend(title.position = "top")) +
new_scale("linetype") +
new_scale_color() +
geom_line(aes(linetype = cyl,
color = cyl)) +
scale_color_discrete(guide = guide_legend(title.position = "top")) +
theme(legend.position = "bottom")

https://stackoverflow.com/questions/68468243
复制相似问题