如果数据属性不为空,如何用不同颜色对点进行着色

问题描述:

我在R中有一个散点图(用ggplot2)。这些数据有一个数字列(我们称之为 bin ),它可以包含各种整数值或为null。

I have a scatter plot in R (with ggplot2). The data has a numeric column (let's call it bin) which can contain various integer values or null.

I想用不同于其他值的非空bin值对点进行着色。我不希望每个箱子的颜色都有一种颜色,那会太嘈杂。简单地说,对于那些带有非空bin的人来说是红色的,对于其他人是黑色的。

I would like to colour the points with non-null bin values differently from the others. I do not want to one colour per value of bin, that would be too noisy. Just simply, say, red for those with a non-null bin and black for the others.

qplot有一个颜色属性,但我不知道如何表达像 color = bin!= null这样的条件? red:black

qplot has a colour attribute, but I don't know how to express a condition like colour = bin != null ? "red" : "black"

您可以先定义颜色:

color <- rep("black", length(bin))
color[is.null(color)] <- "red"

否则,您可以使用ifelse语句:

Otherwise you can use an ifelse statement:

colour=ifelse(is.null(bin), "red", "black")