我有以下两列作为我的数据框的一部分,下面是一个函数:
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
功能:
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))
}
函数调用:
plotM(data, .05) # plots a graph with red points when data$Y < m and black when data$Y > m
但我对以下内容感兴趣:
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
有人可以帮忙吗?感谢
答案 0 :(得分:4)
我们首先生成一些玩具数据:
set.seed(1)
X <- rnorm(100)
Y <- rnorm(100)
您可以执行以下操作:
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)
我们在这里使用cut
返回factor
的事实,并使用级别的数值作为颜色。你也可以这样写:
cols <- as.character(cut(Y, breaks = m, labels = c("Black", "Red", "Green")))
构造颜色。
或者,您可以使用嵌套ifelse
。即。
plot(X, Y, col = ifelse(Y < -0.5, "Red", ifelse(Y > 0.5, "Green", "Black")))
答案 1 :(得分:3)
您可以按如下方式重写您的功能(使用ggplot2
,对于baseplot:见下文):
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)
根据您的数据提供:
使用baseplot,您的功能将如下所示:
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)
给出: