【问题标题】:Is there a way to skip NA values for a line plot in ggplot2有没有办法跳过 ggplot2 中线图的 NA 值
【发布时间】:2021-11-28 05:06:35
【问题描述】:

我正在尝试绘制 4 个共享 y 轴的折线图,但其中一个图有缺失值 (NA)。 我希望能够连接 CI-TR 图的 NA 值两侧的两个点。

这是我正在使用的数据(注意右侧的 CI-TR 具有 NA 值)

这是我的代码,我从 excel 文件中读取了表格:

#read the excel file (same as the table attached)
data <- read_csv("test3.csv", col_types = cols(.default = col_guess())

# gather the data for age and depth
plots <-  data %>% filter(core_id == "BKM0817") %>%
  gather(key = param, value = value, -core_id, -Age, -depth)

#this is to relabel the graph titles (NB the added a is to order alphabetically in the order I want them to appear)
plots %>%  
  mutate(facet_label = fct_recode(
    param,
    "delta ^ 13 * C[OM] ~(`\u2030 V-PDB`)" = "ad13com",
    "delta ^ 15 * N ~(`\u2030 AIR`)" = "d15N",
    "'C/N'" = "C/N",
    "CI-TR" = "aaCI-TR"
  )) %>%
          
# now plot the graphs
  ggplot(aes(y = Age, x = value)) +
  geom_hline(yintercept = c(10720, 10568, 10620), col = "black", alpha = 0.8, lty = 2) +
  geom_lineh(colour = "black", size = 0.5) +
  geom_point(size = 2) +
  facet_wrap(~facet_label, scales = "free_x", labeller = label_parsed, ncol = 4) +
  scale_y_reverse(# Features of the first axis
    name = "Age (Cal. yrs BP)",

 # Add a second axis and specify its features
    sec.axis = sec_axis( trans=~./17.927, name="Depth (cm)")
  ) +
  labs(x = NULL, y = "Age (Cal. yrs BP)") +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))`

【问题讨论】:

  • 删除具有 na 值的行。 na.omit(plots)。由于每个观察都是单行上的链接,因此您应该能够自己删除该点。
  • 如果您不想删除整行(即所有使用 NA 进行观察的值),您可以估算 NA 的上一个或下一个值,这样线就应该直走到下一个实际测量值。或者,您可以用下一个和上一个的平均值对其进行估算,并将其着色以将其标记为“估计”。但是,这意味着您现在在数据/图中已经“发明”了值

标签: r csv ggplot2 linegraph


【解决方案1】:

如果有任何 NA 值,线条几何图形将被切断,因此简单的解决方案是从数据框中删除 NA 值。您可以使用na.omit() 来执行此操作,但只需注意您在代码中使用它的哪里。您的原始数据集如下所示:

df <- data.frame(pos=1:4, A=c(1.05, 2.3, 4.24, 3.89),
  B=c(4.44, NA, 2.22, 3.33))
df

>
  pos    A    B
1   1 1.05 4.44
2   2 2.30   NA
3   3 4.24 2.22
4   4 3.89 3.33

收集后绘制此图:

df %>%
  gather(key=type, value=value, -pos) %>%
  ggplot(aes(x=pos, y=value)) +
  geom_line(linetype=2, color='blue', size=0.7) +
  geom_point(color='red', size=3) +
  facet_wrap(~type)

如果您在df 上使用na.omit(),那么它将删除整个第二行,这也会删除A 列的第二个观察值。在这种情况下,只需确保在 gather() 函数之后使用 na.omit() 将数据框旋转得更长:

df %>%
  gather(key=type, value=value, -pos) %>%
  na.omit() %>%    # important this comes after the gather
  ggplot(aes(x=pos, y=value)) +
  geom_line(linetype=2, color='blue', size=0.7) +
  geom_point(color='red', size=3) +
  facet_wrap(~type)

在您的情况下,下面的伪代码让您知道在您自己的代码中放置na.omit() 的位置:

plots %>%
  mutate(...) %>%
  na.omit() %>%
  ggplot(...) + ...

【讨论】:

  • 感谢您的详细解释!
猜你喜欢
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
  • 1970-01-01
  • 2021-03-07
相关资源
最近更新 更多