【问题标题】:Plot points with 3 different colors具有 3 种不同颜色的绘图点
【发布时间】:2014-06-02 08:32:07
【问题描述】:

我有以下两列作为我的数据框的一部分和下面的一个函数:

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

有人可以帮忙吗?谢谢

【问题讨论】:

  • 使用cut 而不是ifelse

标签: r plot


【解决方案1】:

我们首先生成一些玩具数据:

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")))

【讨论】:

  • cut 有一个 labels 参数,在这里可能很有用。
  • @Roland 好建议。我在答案中添加了对此的评论。
【解决方案2】:

您可以按如下方式重写您的函数(使用ggplot2,对于底图:见下文):

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)

使用您的数据可以得出:


使用底图,您的函数将如下所示:

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)

给出:

【讨论】:

  • 非常感谢 AEBilgrau 和 Jaap。所有解决方案都很棒!现在问题解决了。非常感谢你们!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多