简体   繁体   中英

Adjust ggplot legend

I am trying to make the following changes to the ggplot below (partly illustrated in the picture provided):

  • change shading legend to show economic cycle (shaded is a recession, no shade is an expansion)
  • add additional legend to show economic variables (green is 'CLI' and red is 'Inflation Expectations")

The code so far looks like this:

A <- ggplot(Alldata, aes(Date)) + 
  geom_tile(aes(alpha = Recession, y = 1), 
            fill = "grey", height = Inf) +
  scale_alpha_continuous(range = c(0, 1), breaks = c(0, 1))+
  geom_line(aes(y = stdINFEX), col = 'blue', size = .8)+
  ylab('')+
  theme(        axis.text.y=element_blank(),  #remove y axis labels
        axis.ticks.y=element_blank()  #remove y axis ticks
  )

    
A

B <- A + geom_line(aes(y = CLI), col = 'green', size = .8) 

B

绘图

Maybe this is what you are looking for:

  1. You could set the labels for legend entries via the labels argument of the scale , eg using a named vector you could assign a label Expansion to the value "0"

  2. To get a legend for your lines you have to map on aesthetics, ie move color=... inside of aes() . Note that using color names inside aes() is meaningless. Therefore I would suggest to use meaningful labels. You could then set your desired colors via scale_color_manual .

  3. Finally, to set the labels for your legends you could make use of labs()

As you provided no example data (see how to make a minimal reproducible example ) I make use of the ggplot2::economics dataset as example data:

library(ggplot2)

set.seed(123)

economics$Recession <- 0
economics$Recession[sample(1:nrow(economics), 100)] <- 1

ggplot(economics, aes(date)) +
  geom_tile(aes(alpha = Recession, y = 1),
    fill = "grey", height = Inf
  ) +
  scale_alpha_continuous(range = c(0, 1), 
                         breaks = c(0, 1), 
                         labels = c("0" = "Expansion", "1" = "Recession")) +
  geom_line(aes(y = psavert, color = "psavert"), size = .8) +
  geom_line(aes(y = uempmed, color = "uempmed"), size = .8) +
  scale_color_manual(values = c(psavert = "blue", uempmed = "green")) +
  labs(y = NULL, alpha = "Economic Cycle", color = "Economic Variable") +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank() 
  )

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