Etibar - a tea bar
Etibar - a tea bar

Reputation: 1962

Plot conditional colors based on rows

I have two data.frames called outlier and data.

outlier just keeps row numbers which needs to be coloured. data has 1000 data. It has two columns called x and y. If row number exists in outliers I want dots in plot to be red, otherwise black

plot(data$x, data$y, col=ifelse(??,"red","black"))

Something should be in ?? .

Upvotes: 2

Views: 2222

Answers (2)

Alex Thompson
Alex Thompson

Reputation: 506

Hi this way works for me using ifelse, let me know what you think:

outlier <- sample(1:100, 50)
data <- data.frame(x = 1:100, y = rnorm(n = 100))
plot(
  data[ ,1], data[ ,2]
  ,col = ifelse(row.names(data) %in% outlier, "red", "blue")
  ,type = "h"
)

Upvotes: 1

JHowIX
JHowIX

Reputation: 1803

I think this can be accomplished by creating a new color column in your data frame:

data$color <- "black"

Then set the outliers to a different value:

data[outlier,"color"] <- "red"

I dont have your exact data but I think I got something similar to what you wanted using the following:

outlier <- c(1, 2, 7, 9)
data <- data.frame(x=c(1,2,3,4,5,6,7,8,9,10),
                   y=c(1,2,3,4,5,6,7,8,9,10))
data$color <- "black"
data[outlier,"color"] <- "red"
data
    x  y color
1   1  1   red
2   2  2   red
3   3  3 black
4   4  4 black
5   5  5 black
6   6  6 black
7   7  7   red
8   8  8 black
9   9  9   red
10 10 10 black

Finally plot using the new value in data:

plot(data$x, data$y, col=data$color)

Results in:the following chart

Upvotes: 1

Related Questions