![](/img/trans.png)
[英]How to avoid zig-zag plot when using geom_line with color and linetype
[英]UPDATED: Line Plot Becomes Zig-Zag in R
我有一些關於如何在 R 中使用包含 NA 值的數據的 plot 折線圖的問題。 這是數據的摘錄:
X | 是的 |
---|---|
不適用 | 8 |
3 | 不適用 |
不適用 | 9 |
-3.11 | 2.37 |
-2.90 | 2.45 |
-3.45 | 2.02 |
我嘗試執行以下操作:
plot(na.omit(df$x), na.omit(df$y), type="l",
main="y vs x",
xlab="x",
ylab="y")
我得到這樣的錯誤:
xy.coords(x, y, xlabel, ylabel, log) 錯誤:“x”和“y”長度不同
(a) 我如何 plot 使用基本的 R plot ZC1C425268E47385D1AB579? (b) 我如何使用 GGplot2 plot?
提前致謝。
-更新-
當我 plot 在 R 中繪制折線圖時,該圖從 x=-3.11 變為 x=-2.90 再到 x=-3.45。 如何安排它以使圖形從 x=-3.45 變為 x=-3.11 再到 x=-2.90?
-解決了-
我已經找到了上述問題的解決方案。 只需先對數據框進行排序。 df <- df[order(df$x), ]
使用基本圖形
plot(na.omit(df)["x"], na.omit(df)["y"])
使用 ggplot
ggplot(na.omit(df),aes(y=y,x=x))
# your data
x <- c(7, NA, 90, 3, 57, NA)
y <- c(9,8,4,NA, 9, 9)
# 1.)
plot(x~y, type="b", data=na.omit(data.frame(x,y)))
# 2.)
plot(x~y, type="b", subset=complete.cases(x,y))
# 3.)
s <- complete.cases(x,y)
plot(y[s], x[s], type="b")
@mochalatte,回答評論中的問題:
~(波浪號)運算符表征 R 中的公式。 左側的變量(在我們的示例中為 x)是因變量。右側的變量(在我們的示例中為 y)是自變量。 通常,因變量 x 由一個或多個自變量探索。 如果你像 y~x 一樣改變,那么你的因變量和自變量也會發生變化。 請參閱: 在 R 編程語言和R 公式中使用 ~(波浪號),為什么我必須使用 I() function) 冪項,例如
subset=complete.cases(x,y) 的含義:
在我們的例子中 x,y 沒有 NA。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.