简体   繁体   中英

overlaying plots in ggplot2

How to overlay one plot on top of the other in ggplot2 as explained in the following sentences? I want to draw the grey time series on top of the red one using ggplot2 in R (now the red one is above the grey one and I want my graph to be the other way around). Here is my code (I generate some data in order to show you my problem, the real dataset is much more complex):

install.packages("ggplot2")
library(ggplot2)

time <- rep(1:100,2)
timeseries <- c(rep(0.5,100),rep(c(0,1),50))
upper <- c(rep(0.7,100),rep(0,100))
lower <- c(rep(0.3,100),rep(0,100))
legend <- c(rep("red should be under",100),rep("grey should be above",100))

dataset <- data.frame(timeseries,upper,lower,time,legend)

ggplot(dataset, aes(x=time, y=timeseries)) +
  geom_line(aes(colour=legend, size=legend)) +
  geom_ribbon(aes(ymax=upper, ymin=lower, fill=legend), alpha = 0.2) +
  scale_colour_manual(limits=c("grey should be above","red should be under"),values = c("grey50","red")) +
  scale_fill_manual(values = c(NA, "red")) +
  scale_size_manual(values=c(0.5, 1.5)) +
  theme(legend.position="top", legend.direction="horizontal",legend.title = element_blank())

Convert the data you are grouping on into a factor and explicitly set the order of the levels. ggplot draws the layers according to this order. Also, it is a good idea to group the scale_manual codes to the geom it is being applied to for readability.

legend <- factor(legend, levels = c("red should be under","grey should be above"))

c <- data.frame(timeseries,upper,lower,time,legend)

ggplot(c, aes(x=time, y=timeseries)) +
  geom_ribbon(aes(ymax=upper, ymin=lower, fill=legend), alpha = 0.2) +
  scale_fill_manual(values = c("red", NA)) +
  geom_line(aes(colour=legend, size=legend)) +
  scale_colour_manual(values = c("red","grey50")) +
  scale_size_manual(values=c(1.5,0.5)) +
  theme(legend.position="top", legend.direction="horizontal",legend.title = element_blank())

Note that the ordering of the values in the scale_manual now maps to "grey" and "red"

在此处输入图片说明

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