具有不等长向量的R ggplot2绘图循环

时间:2018-10-25 18:04:14

标签: r vector ggplot2 plot rstudio

我有一个示例数据帧,其中包含多个不等长的向量(例如,有些长度为5个数据点,有些为3个,依此类推。我有一个循环为每一列生成一个ggplot。但是,我无法弄清楚如何动态地缺少数据时缩短绘图。

数据示例:

        date        X1        X2        X3
1 1997-01-31 0.6094410        NA 0.5728303
2 1997-03-03 0.7741195        NA 0.0582721
3 1997-03-31 0.7269925 0.5628813 0.8270764
4 1997-05-01 0.5471391 0.5381265 0.8678812
5 1997-05-31 0.8056487 0.4129166 0.6582061

到目前为止的代码:

vars <- colnames(data[-1])
plots <- list()

for (x in 1:length(vars)) {
  plot[[x]] <- ggplot(data = data, aes_q(x = data[, 1], y = data[, x + 1])) + 
    geom_line()
}

绘制第一个图可获得良好的结果:

Plot 1

但是,绘制第二个图会产生以下短线:

Plot 2

如何更改循环以使第二幅图是这样?:

Plot 3

先谢谢您!感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在指定要用于y轴的列之前,ggplot将准备映射到整个数据框。因此,如果您仅输入ggplot(data, aes(x = date)),您将已经得到一个具有该范围的空白图:

enter image description here

因此,如果您不希望某个系列来打印整个范围,则必须首先将数据集过滤到要用于y值的列所定义的行中。例如,您可以使用以下命令创建X2图:

temp <- data[complete.cases(data[c(1,3)]), c(1,3)]
ggplot(temp, aes(x = date, X2)) + geom_line()

我喜欢使用dplyrtidyr来做到这一点:

library(dplyr); library(tidyr)
temp <- data %>% select(date, X2) %>% drop_na()
ggplot(temp, aes(x = date, X2)) + geom_line()

enter image description here

要对所有变量执行此操作,以下是将dplyrtidyrpurrr结合使用的方法:

library(purrr); library(dplyr); library(tidyr)
plots <- data %>% 
  # Convert to long form and remove NA rows
  gather(var, value, -date) %>%
  drop_na() %>%

  # For each variable, nest all the available data
  group_by(var) %>%
  nest() %>%

  # Make a plot based on each nested data, where we'll use the
  #   data as the first parameter (.x), and var as the second
  #   parameter (.y), feeding those into ggplot.
  mutate(plot = map2(data, var, 
                     ~ggplot(data = .x, aes(date, value)) +
                       geom_line() +
                       labs(title = .y, y = .y)))

# At this point we have a nested table, with data and plots for each variable:
plots
# A tibble: 3 x 3
  var   data             plot    
  <chr> <list>           <list>  
1 X1    <tibble [5 x 2]> <S3: gg>
2 X2    <tibble [3 x 2]> <S3: gg>
3 X3    <tibble [5 x 2]> <S3: gg>

# To make this like the OP, we can extract just the plots part, with
plots <- plots %>% pluck("plot")
plots

plots[[1]]
plots[[2]] # or use `plots %>% pluck(2)`
plots[[3]]

enter image description here enter image description here enter image description here