I am having a bit of trouble getting my legend title to center over my legend when it is on the bottom. I can only do it if I change the legend to vertical instead of horizontal. Here is my code and the result, as it stands:
#1990
ggplot()
geom_sf(data = tracts, mapping = aes(fill = pop.compare), show.legend = TRUE)
scale_fill_stepsn(colours = c("#fde725", "#addc30", "#5ec962", "#28ae80","#21918c", "#2c728e", "#3b528b", "#472d7b", "black"),
limits = c(0,227),
breaks = c(0.25, 0.75, .9, 1.1, 1.25, 2, 3, 10),
values = scales::rescale(c(0.115, 0.5, 0.825, 1, 1.175, 1.5, 2.5, 6.5, 118.5),
from = c(0,227)))
labs(fill = "Population Ratio")
theme(plot.title = element_text(hjust = 0.5),
legend.position = "bottom",
legend.key.width = unit(1.5,"cm"),
legend.spacing = unit(0.25,"cm"),
legend.title = element_text(hjust = 0.5),
legend.justification = "center")
guides(colour=guide_legend(title.position="top"))
coord_sf()
EDIT: Per@stefan's comment below, I added:
guides(fill=guide_legend(title.position="top"))
Which does center the legend title over the legend, but also reconfigures it in a weird way that I don't want, see updated image below
CodePudding user response:
Solution:
Per @stefan's advice, using fill=guide_coloursteps makes it possible to specify the legend title location. The solution and result I used is below
#1990
ggplot()
geom_sf(data = tracts, mapping = aes(fill = pop.compare), show.legend = TRUE)
scale_fill_stepsn(colours = c("#fde725", "#addc30", "#5ec962", "#28ae80","#21918c", "#2c728e", "#3b528b", "#472d7b", "black"),
limits = c(0,227),
breaks = c(0.25, 0.75, .9, 1.1, 1.25, 2, 3, 10),
values = scales::rescale(c(0.115, 0.5, 0.825, 1, 1.175, 1.5, 2.5, 6.5, 118.5),
from = c(0,227)))
labs(fill = "Population Ratio")
theme(plot.title = element_text(hjust = 0.5),
legend.position = "bottom",
legend.key.width = unit(1.5,"cm"),
legend.spacing = unit(0.25,"cm"),
legend.title = element_text(hjust = 0.5),
legend.justification = "center")
guides(fill=guide_coloursteps(title.position="top"))
coord_sf()
Other resources, as noted by @phalteman:



