[英]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.