如何使用ggplot连接包含NA的观测值进行分面?

时间:2017-11-13 16:02:22

标签: r ggplot2 facet-wrap facet-grid

目的是使用ggplot和facet选项

来使用包含NA的连接观察
df <- data.frame(
    time = 1:5,
    y1 = c(4, 2, 3, 1, NA),
    y2 = c(4, 5, NA, 6, 10),
    y3 = c(8, 7, NA, 4, 5)
  )

  library(ggplot2)
  ggplot(df, aes(x=time, y=y2)) + geom_line() # no connection between observations

  ggplot(na.omit(df), aes(x=time, y=y2)) + geom_line() # a way to connect is to omit NAs but this works only when one variable 

  library(tidyr)
  df2 <- df %>% gather(key = "var", value = "values", 2:4)  # gather values from variables

  ggplot(df2, aes(x=time, y=values, colour = var)) + geom_line()+
  facet_wrap(~ var) # no connection between observations ==> issue !

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用gather功能删除NA值后,您可以设置library(tidyr) df2 <- df %>% gather(key = "var", value = "values", 2:4, na.rm = TRUE) ggplot(df2, aes(x = time, y = values, colour = var)) + geom_line() + facet_wrap(~var) ,然后绘制数据。

driver:
  name: ec2
  instance_type: t2.medium
  region: us-east-1
  security_group_ids:
    - sg-1234567abcd
  subnet_id: subnet-12345677
  tags:
    Name: 'test-kitchen WinCustomAMI'
    Environment: 'test'
    SN Project: 'Custom AMI'
    SN Platform: 'Windows 2012R2'
    SN Owner: 'Some Team'

enter image description here