簡體   English   中英

為什么 geom_line 中間的 NA 並不總是斷線?

[英]Why does NA in the middle of a geom_line not always break the line?

我的問題與這個問題有關:

使用分類數據創建線圖而不是連接線

這是鏈接問題中的示例:

library(ggplot2)
df <- data.frame(x = c('a', 'b', 'c', 'd', 'e'), 
                 y = c('a', 'a', NA, 'a', 'a'))

ggplot(df, aes(x = x, y = y, group = y)) +
  geom_point() + 
  geom_line()

雖然df$y包含NA ,但繪制了一條連續線:

is.na(df$y)
[1] FALSE FALSE  TRUE FALSE FALSE

我很困惑,因為在缺少值處理下的geom_line()幫助中,它說:

geom_path()、geom_line() 和 geom_step 處理 NA 如下:

如果 NA 出現在一行的中間,它會斷開該行。 無論 na.rm 是 TRUE 還是 FALSE,都不會顯示警告。

誰能向我解釋為什么這不適用於上面示例中的分類數據?

通過嘗試,我猜這與group部分有關,但我真的不明白這是如何工作的。 非常感謝你的幫助!

編輯:
與我假設的不同,數據是分類數據還是數字數據並不重要。 看:

ggplot(df, aes(x = as.numeric(as.factor(x)), y = as.numeric(as.factor(y)), group = as.numeric(as.factor(y)))) +
  geom_point() + 
  geom_line()

這只會刪除NA point ,但會繼續在中斷上繪制線。 事實上,關鍵點是分組,這對於數值數據不是必需的:

ggplot(df, aes(x = as.numeric(as.factor(x)), y = as.numeric(as.factor(y)))) +
  geom_point() + 
  geom_line() 

請參閱下面的評論。

確實有趣的是,它對連續數據和分類數據的工作方式不同,但考慮到這些數據的不同性質,它有點道理。

在不使用rle ,一種解決方法可以是分解並使用因子水平進行繪圖。 然后您可以使用scale更改標簽

用戶 Edward的評論是正確的 - 分組非常相關。 這里我使用了group = 1

library(ggplot2)
df <- data.frame(x = c('a', 'b', 'c', 'd', 'e'), 
                 y = c('a', 'a', NA, 'a', 'a'))

ggplot(df, aes(x = x, y = as.numeric(as.factor(y)), group = 1)) +
  geom_point() + 
  geom_line() +
  scale_y_continuous(breaks = 1, labels = 'a')
#> Warning: Removed 1 rows containing missing values (geom_point).

reprex 包(v0.3.0) 於 2020 年 3 月 4 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM