2014-07-20 129 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

謝謝 - 非常好用! –