简体   繁体   English

更新:Plot 线在 R 中变为锯齿形

[英]UPDATED: Line Plot Becomes Zig-Zag in R

I have some question regarding how to plot line graph in R with data containing NA value.我有一些关于如何在 R 中使用包含 NA 值的数据的 plot 折线图的问题。 Here is an extract of the data:这是数据的摘录:

x X y是的
NA不适用 8 8
3 3 NA不适用
NA不适用 9 9
-3.11 -3.11 2.37 2.37
-2.90 -2.90 2.45 2.45
-3.45 -3.45 2.02 2.02

I tried to do the following:我尝试执行以下操作:

plot(na.omit(df$x), na.omit(df$y), type="l", 
 main="y vs x",
 xlab="x",
 ylab="y")

I got the error like this:我得到这样的错误:

xy.coords(x, y, xlabel, ylabel, log) Error: 'x' and 'y' lengths differ xy.coords(x, y, xlabel, ylabel, log) 错误:“x”和“y”长度不同

(a) How do I plot using the basic R plot function? (a) 我如何 plot 使用基本的 R plot ZC1C425268E47385D1AB579? (b) How do I plot using the GGplot2? (b) 我如何使用 GGplot2 plot?

Thanks in advance.提前致谢。

-Updated- -更新-

When I plot a line graph in R, the graph goes from x=-3.11 to x=-2.90 to x=-3.45.当我 plot 在 R 中绘制折线图时,该图从 x=-3.11 变为 x=-2.90 再到 x=-3.45。 How do I arrange it so that the graph goes from x=-3.45 to x=-3.11 to x=-2.90?如何安排它以使图形从 x=-3.45 变为 x=-3.11 再到 x=-2.90?

-Solved- -解决了-

I have found the solution to the above question.我已经找到了上述问题的解决方案。 Just sort the data frame first.只需先对数据框进行排序。 df <- df[order(df$x), ] df <- df[order(df$x), ]

Using base graphics使用基本图形

plot(na.omit(df)["x"], na.omit(df)["y"])

using ggplot使用 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, Answer to questions in the comment: @mochalatte,回答评论中的问题:

The ~ (tilde) operator characterizes formulas in R. ~(波浪号)运算符表征 R 中的公式。 The variable on the left (in our example x) is the dependent variable.The variable on the right side (in our example y) is the independent variable.左侧的变量(在我们的示例中为 x)是因变量。右侧的变量(在我们的示例中为 y)是自变量。 Usually a dependent variable x is explored by one or more independent variables.通常,因变量 x 由一个或多个自变量探索。 If you change like y~x then your dependent and independent variable is also changing.如果你像 y~x 一样改变,那么你的因变量和自变量也会发生变化。 see: Use of ~ (tilde) in R programming Language and In R formulas, why do I have to use the I() function on power terms, like y ~ I(x^3)请参阅: 在 R 编程语言R 公式中使用 ~(波浪号),为什么我必须使用 I() function) 幂项,例如

Meaning of subset=complete.cases(x,y): subset=complete.cases(x,y) 的含义:

  • complete.cases: returns a logical vector indicating which cases are complete, ie, have no missing values. complete.cases:返回一个逻辑向量,指示哪些案例是完整的,即没有缺失值。
  • subset: returns subsets of vectors, matrices or data frames which meet conditions.子集:返回满足条件的向量、矩阵或数据帧的子集。

In our case x,y without NA.在我们的例子中 x,y 没有 NA。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM