[英]Colour R plot for binomial variable
I've created a plot with a binomial variable, which has values of 0 and 1. In the resulting plot, I want to clearly see which of the circles in the plot belong to the category 0 and which to 1. I am able to给圆圈不同的颜色,但不要按照我刚才提到的方式。 有人碰巧知道如何完成这项工作吗?
在基础 R 中, plot
function 采用确定点颜色的参数col
。 考虑以下:
# generate some random data to plot
dataPoints = runif(50)
# plot all points as green points
plot(dataPoints, col = "green", pch = 20)
现在让我们为每个点创建一个随机二项式“类型”(0 或 1):
# generate a random "type" for each point; either 0 or 1
dataType = sample(c(0,1), 50, replace = T)
使用二项式,我们可以制作一个colors的向量,而不是仅仅指定一个颜色:
# create a list of colors for each point, based on "type" of point (0 or 1).
# 0 = "red" and 1 = "blue".
colorVector = c("red", "blue")[dataType+1]
看看内容...
> dataType
[1] 1 1 1 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 1 1 1 0 0 0 1 0 0 0 0 0 0 1 1 1 1 0 0 1 1 1 0
> colorVector
[1] "blue" "blue" "blue" "red" "red" "blue" "red" "red" "blue" "red" "red" "blue" "red" "red" "red" "red"
[17] "red" "red" "red" "blue" "blue" "red" "red" "red" "blue" "blue" "red" "blue" "blue" "blue" "red" "red"
[33] "red" "blue" "red" "red" "red" "red" "red" "red" "blue" "blue" "blue" "blue" "red" "red" "blue" "blue"
[49] "blue" "red"
现在,告诉plot
使用 colors 的颜色向量——第一个点将是颜色向量中的第一个颜色,第二个点将是颜色向量中的第二个颜色,等等。
plot(dataPoints, col = colorVector, pch = 20)
最后,如果 colors 的列表比点的列表短,则颜色向量被回收......
plot(1:30, col = c("red", "blue", "green"), pch = 20)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.