R ggplot2绘制具有不等长度矢量的循环

问题描述 投票:0回答:1

我有一个带有几个不等长度向量的示例数据帧(即一些是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

先感谢您!任何帮助表示赞赏

r vector ggplot2 plot rstudio
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.