Using Conditional Statements to Change the Color of Data Points

风流意气都作罢 提交于 2019-12-01 03:51:37

问题


I have a data set, which I have used to make a scatter plot and I would like to assign three different colors to the data points within three different regions, based on their x values.

Data points with x-values < 3 I want to appear red

Data points with x-values (3,1549) I want to appear black

Data points with x values >1549 I want to appear purple

Here is my code for the scatterplot and accomplishing the first two parameters, how might I implement the third parameter, so that the last region's data points will be purple?

plot(x, y, xlab="chr X position (Mb)",
           ylab="Diversity",
           pch=16, cex =0.7, 
           col = ifelse(x < 3,'red','black'))    


回答1:


Just use nested ifelses:

plot(...., col=ifelse(x < 3, "red", ifelse(x > 1549, "purple", "black")))



回答2:


Also, the "classic" findInterval:

col = c("red", "black", "purple")[findInterval(x, v = c(0,3,1549))]




回答3:


You can define a vector of colors and pass it to the col argument of plot. Something like this :

colors <- rep("black", length(x))
colors[x<3] <- "red"
colors[x>1549] <- "pink"

plot(x, y, xlab="chr X position (Mb)",
           ylab="Diversity",
           pch=16, cex =0.7, 
           col = colors)    



回答4:


I like the cut approach:

set.seed(1)
x <- sample(1600)
col <- c("red", "black", "purple")
col <- col[cut(x, breaks=c(-Inf, 3, 1549, Inf))]


来源:https://stackoverflow.com/questions/19375977/using-conditional-statements-to-change-the-color-of-data-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!