I created a plot which has 2 color scales and 2 linetype scales made with the ggnewscale
package. I want the legend to appear at the bottom of the plot and the legend titles to appear above the labels. I did it halfway, because in my attempts, the first scales (from geom_vline()
) don't appear the way I want. I even tried to indicate the desired position of this scale before declaring the next scales with new_scale()
and new_scale_color()
.Does anyone know how I can fix this?
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"))
Both attempts produce the same plot, which is not what I want.