简体   繁体   中英

GGPLOT - Order of Multiple legends (geom_line and geom_line plus geom_point)

I searched for many questions already answered, but none of them can help me.

This is my code:

ggplot(z, aes(x=`Fecha de muestreo`, y = Valor, color = `Nombre de la estación`)) + 
  geom_line(size = 0.4) + 
  geom_point(size=0.5) + 
  scale_x_date(date_labels = "%b", breaks = "1 month", limits = c(as.Date("2019-1-1"), as.Date("2019-12-20"))) + 
  scale_y_continuous("pH (unidades de pH)", limits = c(3, 11), breaks = c(3:11)) +
  geom_hline(aes(yintercept = 6.5, linetype = "ECA cat.3 inf D1 y D2 : 6.5"), colour = "Blue", size = 0.4)+
  geom_hline(aes(yintercept = 8.4, linetype = "ECA cat.3 sup. D1 : 8.4"), colour = "Green", size = 0.4)+
  geom_hline(aes(yintercept = 8.5, linetype = "ECA cat.3 sup. D2 : 8.5"), colour = "red", size = 0.4)+
  scale_linetype_manual(name = NULL, values = c(1, 1, 1), # values = tipo de lineas
                        guide = guide_legend(override.aes = list(color = c("blue", "Green", "Red")))) +
  theme(axis.text=element_text(size=6), 
        legend.margin = unit(-0.2, "cm"),
        axis.title=element_text(size=7,face="bold")) +
  theme(legend.text=element_text(size=6), 
        legend.title = element_blank(), 
        legend.spacing.x = unit(.2, 'cm')) + 
  theme(legend.key = element_rect(fill = "white")) +
  theme(panel.background = element_rect(fill = "white")) +
  theme(panel.grid = element_line(colour= "gray"))

This is the graph:

在此处输入图片说明

I need to change the order of the legends: the "ECAS" should be at the bottom. How can I do it?

This should be possible using the order term of guides() . For example:

library(ggplot2)
a <- ggplot(mtcars, aes(wt, mpg, 
                   color = as.character(cyl), 
                   fill = as.character(gear))) +
  geom_point(size = 5, shape = 21, stroke = 2) +
  scale_color_discrete(name = "cyl as color") +
  scale_fill_discrete(name = "gear as fill")
a  

在此处输入图片说明

To reverse the order, we can add: (note, ordering seems to be from the bottom up)

a +
  guides(color = guide_legend(order = 0),
         fill  = guide_legend(order = 1))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM