本文介绍了ggplot在R中使用多个data.frame的facet_wrap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在与 D1 相同的图上进行 ggplot D2 .但是,我在 D2 data.frame 中没有变量 X 的数据.我如何在 D1绘图的相应 facets 上绘制 D2 ?这些图表示 2011 2014 的数据,因此我想为 line 使用 legends ,以区分哪个 line 代表哪个 year 数据.

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 ?

推荐答案

如何将两个DF转换为长格式,然后在绘图之前将它们合并在一起?

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'))

这篇关于ggplot在R中使用多个data.frame的facet_wrap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 22:24