2014-07-20 128 views
-2

我有一个数据框,包含3列数据,我想分开绘制 - 3个绘图。数据中有NA(在3列中的不同位置)。我基本上想要插入缺失的值,并将该线段(多个部分)以红色和线条的其余部分绘制成黑色。R - if for循环内的语句

我已经设法使用'动物园'创建插值数据,但我不确定如何绘制这个数据点不同的颜色。我发现以下Elegant way to select the color for a particular segment of a line plot? 但我想我可以使用for循环与if语句创建颜色列建议在链接 - 我需要3个独立的颜色列,因为我有3个数据集。

欣赏任何帮助 - 无法真正提供示例,因为我不确定从哪里开始!谢谢

+2

我建议你准备一个可重复使用的小例子。以下是关于如何进行的一些提示。 http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example –

+0

几乎总是这样的情况下,来自SAS或SPSS工作R的人不正确地达到'for (){if(){} else {}}'当他们应该首先查看'?ifelse'。 –

+0

感谢BondedDust - 我让它太复杂了,我同意。 UN.GRACE $ Col < - ifelse(is.na(UN.GRACE [2:4]),“red”,“black”) –

回答

1

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

如果您将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") 

干杯。

+0

谢谢 - 非常好用! –