R - if for循环中的else语句

时间:2014-07-20 15:23:17

标签: r if-statement for-loop plot

我有一个包含3列数据的数据框,我想分别绘制 - 3个图。数据中包含NA(在3列中的不同位置)。我基本上想要插入缺失值并将该线段(多个部分)绘制成红色,将剩余部分绘制为黑色。

我设法使用动物园'创建插值数据但不确定如何将此数据点绘制成不同的颜色。我找到了以下Elegant way to select the color for a particular segment of a line plot? 但我想我可以使用if循环使用if else语句来创建链接中建议的颜色列 - 我需要3个单独的颜色列,因为我有3个数据集。

感谢任何帮助 - 无法真正提供一个例子,因为我不确定从哪里开始!感谢

1 个答案:

答案 0 :(得分:1)

这是我的解决方案。它假定NA仍然存在于原始数据中。这些将在第一个plot()命令中省略。然后该函数仅遍历NA s。

如果从函数中取出plot()命令,您可能会得到更好的控制。如上所述," ..."传递给plot()并模仿type = "b"图表 - 但将其更改为您想要的任何内容都是微不足道的。

# Function to plot interpolated valules in specified colours.
PlotIntrps <- function(exxes, wyes, int_wyes, int_pt = "red", int_ln = "grey",
      goodcol = "darkgreen", ptch = 20, ...) {

  plot(exxes, wyes, type = "b", col = goodcol, pch = ptch, ...)

  nas <- which(is.na(wyes))
  enn <- length(wyes)

  for (idx in seq(nas)) {
    points(exxes[nas[idx]], int_wyes[idx], col = int_pt, pch = ptch)
    lines(
      x = c(exxes[max(nas[idx] - 1, 1)], exxes[nas[idx]],
        exxes[min(nas[idx] + 1, enn)]),
      y = c(wyes[max(nas[idx] - 1, 1)], int_wyes[idx],
        wyes[min(nas[idx] + 1, enn)]),
      col = int_ln, type = "c")

    # Only needed if you have 2 (or more) contiguous NAs (interpolations)
    wyes[nas[idx]] <- int_wyes[idx]
  }
}

# Dummy data (jitter() for some noise)
x_data <- 1:12
y_data <- jitter(c(12, 11, NA, 9:7, NA, NA, 4:1), factor = 3)
interpolations <- c(10, 6, 5)

PlotIntrps(exxes = x_data, wyes = y_data, int_wyes = interpolations, 
  main = "Interpolations in pretty colours!",
  ylab = "Didn't manage to get all of these")

干杯。