ggplot using facet_wrap of multiple data.frame in R?

 ̄綄美尐妖づ 提交于 2021-01-28 04:01:03

问题


I am trying to ggplot D2 on the same figure as of D1. I, however, do not have data for the Variable X in D2 data.frame. How i can plot D2 on its respective facets of D1 plot? these plots represent data for 2011 and 2014 so i would like to have legends for the line to differentiate which line represent which year data.

library(tidyverse)

set.seed(1500)

D1 <- data.frame(Day = 1:8, A = runif(8, 2,16), S = runif(8, 3,14), X = runif(8, 5,10), Z = runif(8, 1,12), Year = rep("2011",8))
D2 <- data.frame(Day = 1:8, A = runif(8, 2,14), S = runif(8, 1,13),  Z = runif(8, 3,14), Year = rep("2014",8))

# plotting D1
 D1 %>% gather(-c(Day, Year), key = "Variable", value = "Value") %>% 
  ggplot( aes(x = Day, y = Value))+
  geom_line()+facet_wrap(~Variable,  scales = "free_y", nrow=2)

# Plotting D2 on top ?

回答1:


How about convert two DFs to long format then merge them together before plotting?

library(tidyverse)

set.seed(1500)

D1 <- data.frame(Day = 1:8, A = runif(8, 2,16), S = runif(8, 3,14), 
                 X = runif(8, 5,10), Z = runif(8, 1,12), Year = rep("2011",8))
D1_long <- D1 %>% 
  pivot_longer(-c(Day, Year),
               names_to = 'Variable',
               values_to = 'Value')

D2 <- data.frame(Day = 1:8, A = runif(8, 2,14), S = runif(8, 1,13),  
                 Z = runif(8, 3,14), Year = rep("2014",8))
D2_long <- D2 %>% 
  pivot_longer(-c(Day, Year),
               names_to = 'Variable',
               values_to = 'Value')

### merge two data frames
DF <- bind_rows(D1_long, D2_long)

my_linetype <- setNames(c("dashed", "solid"), unique(DF$Year))

# plot DF
DF %>% 
  ggplot(aes(x = Day, y = Value, 
             color = Year,
             linetype = Year))+
  geom_line() +
  facet_wrap(~ Variable,  scales = "free_y", nrow = 2) +
  scale_color_brewer(palette = 'Dark2') +
  scale_linetype_manual(values = my_linetype) +
  theme_bw(base_size = 14) +
  theme(legend.position = 'bottom') +
  theme(legend.key.size = unit(2.5, 'lines'))

Created on 2020-07-15 by the reprex package (v0.3.0)



来源:https://stackoverflow.com/questions/62924850/ggplot-using-facet-wrap-of-multiple-data-frame-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!