【问题标题】:R ggplot2 Plotting Loop with Unequal Length VectorsR ggplot2用不等长向量绘制循环
【发布时间】:2018-10-25 18:04:14
【问题描述】:

我有一个带有几个不等长向量的示例数据框(即,有些是 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) 停止使用 data 作为对象名称。 2) 子集传递给data 参数的参数。目前,您正在为绘图例程提供一整列日期。
  • 如果将na.omit(data) 添加到geom_line 调用中会发生什么?

标签: r vector ggplot2 plot rstudio


【解决方案1】:

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

因此,如果您不希望某些系列打印整个范围,则必须首先过滤数据集,过滤到为您将用于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()

要对所有变量执行此操作,这是一种使用 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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2018-04-03
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多