Home > other >  Plot two lines on one graph on left panel and their difference on the right panel using facet_wrap o
Plot two lines on one graph on left panel and their difference on the right panel using facet_wrap o

Time:05-01

I have the following data frames:

df1 <- data.frame(a= c(1:10), x= c(0.1, 0.5, 0.2, 0.1, 0, 0.23, 0.25, 0.4, 0.01, 0.2),
             y= c(0.3,0.01, 0.8, 0.2, 0.02, 0.14, 0.47, 0.35, 0, 0.32), name="L1")
df2 <- data.frame(a= c(1:10), x= c(0.2, 0.25, 0.2, 0.1, 0, 0.23, 0.25, 0.4, 0.01, 0.2),
                 y= c(0.76,0.81, 0.18, 0.52, 0.02, 0.14, 0.47, 0.35, 0, 0.32), name="L2")

I want to use either facet_wrap or facet_grid to get the following plot: enter image description here

On the left hand panel, I want to plot both variables x and y on one graph, and on the right hand panel, I want to plot the difference between x and y using two methods, L1 and L2.

I have tried the following codes:

library(ggplot2)
library(reshape)

df3 <- melt(df1, id = c("a", "name"))
df4 <- melt(df2, id = c("a", "name"))

df5 <- rbind(df3, df4)
ggplot() geom_line(data = df5, aes(x=a, y=value, color= variable)) 
 facet_grid(name ~ variable) 
  geom_line(data = df1, aes(x=a, y=y)) 
  geom_line(data = df2, aes(x=a, y=y))

ggplot() 
  geom_line(data = df1, aes(x=a, y= x-y), color= "green")

ggplot() 
  geom_line(data = df2, aes(x=a, y= x-y), color= "green")

I was unable to complete my assignment. Any assistance would be greatly appreciated.

CodePudding user response:

For easier handling, I would create the x - y column before melt. Then we need to create a column (in my code group) for facet_grid. The factor operation sets the position of the facet, so that x and y would be on the left hand side of x - y. Finally, set colors with scale_color_manual.

library(ggplot2)
library(dplyr)
library(reshape2)

df1 <- data.frame(a= c(1:10), x= c(0.1, 0.5, 0.2, 0.1, 0, 0.23, 0.25, 0.4, 0.01, 0.2),
                  y= c(0.3,0.01, 0.8, 0.2, 0.02, 0.14, 0.47, 0.35, 0, 0.32), name="L1")
df2 <- data.frame(a= c(1:10), x= c(0.2, 0.25, 0.2, 0.1, 0, 0.23, 0.25, 0.4, 0.01, 0.2),
                  y= c(0.76,0.81, 0.18, 0.52, 0.02, 0.14, 0.47, 0.35, 0, 0.32), name="L2")

rbind(df1, df2) %>% 
  mutate(`x - y` = x - y) %>% 
  melt(id = c("a", "name")) %>% 
  mutate(group = if_else(variable %in% c("x", "y"), "x and y", "x - y"),
         group = factor(group, levels = c("x and y", "x - y"))) %>% 
  ggplot(aes(a, value, col = variable))   
  geom_line()   
  facet_grid(name ~ group)  
  scale_color_manual(values = c("x" = "red", "y" = "black", "x - y" = "green"))

Created on 2022-05-01 by the reprex package (v2.0.1)

  • Related