如何使用 ggplot 连接包含 NA 的观测值进行分面?
How to connect observations containing NAs using ggplot for facetting?
只是为了使用 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 !
有什么想法吗?
在使用gather
函数时可以设置na.rm = TRUE
去掉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)
只是为了使用 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 !
有什么想法吗?
在使用gather
函数时可以设置na.rm = TRUE
去掉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)