Reputation: 903
I have the following two columns as part of my dataframe and a function below:
X
705.7553
789.2789
689.7431
559.8025
629.9365
564.9095
Y
-0.0596123270783229
0.644158691971081
-0.433854284204926
-0.365746109442603
0.566685929975495
0.398462720589891
Function:
plotM<- function( all.res, m, u ) {
plot(data$X, data$Y,
log="x", pch=20, cex=0.7,
col = ifelse( data$Y < m, "red", "black" ),
xlab = "Y", ylab = expression(Log[2]~Fold~Change))
}
Function call:
plotM(data, .05) # plots a graph with red points when data$Y < m and black when data$Y > m
But I'm interested in the following:
plotM(data, 0.05, 0.1 ) # to plot a graph with red points when data$Y < m, green when data$Y > u, and the rest colored black
Can anyone help please? Thanks
Upvotes: 1
Views: 3597
Reputation: 83225
You can rewrite your function as follows (utilizing ggplot2
, for baseplot: see below):
plotM <- function(data, m, u){
data$cols <- ifelse(data$Y < m, "1", ifelse(data$Y > u, "2", "3"))
ggplot(data, aes(x = X, y = Y, color = cols)) +
geom_point(size=3) +
scale_color_manual(breaks = c(1,2,3), values = c("red","green","black"),
labels = c("red","green","black")) +
theme_bw()
}
plotM(data, 0.05, 0.4)
with your data this gives:
With the baseplot your function will look like:
plotBase <- function(data,m,u){
data$cols <- ifelse(data$Y<m,"red",ifelse(data$Y>u,"green","black"))
plot(data$X, data$Y, col=data$cols, pch=20)
}
plotBase(data,0.05,0.4)
which gives:
Upvotes: 3
Reputation: 10223
We first generate some toy data:
set.seed(1)
X <- rnorm(100)
Y <- rnorm(100)
You can do something like:
m <- c(-Inf, -0.5, 0.5, Inf) # Specify your cut points, here -0.5 and 0.5
cols <- cut(Y, breaks = m)
plot(X, Y, col = cols)
We here use the fact that cut
returns a factor
, and use the numeric values of the levels as colors. You could also write something like:
cols <- as.character(cut(Y, breaks = m, labels = c("Black", "Red", "Green")))
to construct the colours.
Alternatively, you can use nest ifelse
. I.e.
plot(X, Y, col = ifelse(Y < -0.5, "Red", ifelse(Y > 0.5, "Green", "Black")))
Upvotes: 4