简体   繁体   English

ggplot在R中使用多个data.frame的facet_wrap?

[英]ggplot using facet_wrap of multiple data.frame in R?

I am trying to ggplot D2 on the same figure as of D1 .我试图ggplot D2D1相同。 I, however, do not have data for the Variable X in D2 data.frame .但是,我在D2 data.frame中没有变量X的数据。 How i can plot D2 on its respective facets of D1 plot ?我如何在D1 plot的各个facets plot D2 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.这些图代表20112014的数据,所以我想有linelegends来区分哪line代表哪year数据。

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 ?

How about convert two DFs to long format then merge them together before plotting?如何将两个 DF 转换为长格式,然后在绘图之前将它们合并在一起?

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)代表 package (v0.3.0) 于 2020 年 7 月 15 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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