简体   繁体   English

R中图的着色点

[英]Colouring points of a plot in R

I'm trying to colour certain points of a scatter plot in R using logical arguments. 我正在尝试使用逻辑参数为R中的散点图的某些点着色。 My data is a function of sex( M/F ) and faculty (A/M/S/E). 我的数据是性别(M / F)和教职人员(A / M / S / E)的函数。 I want to colour each faculty, say green, red, blue, black, and then have the females showing as outline only, with a white center. 我想给每个系上色,比如说绿色,红色,蓝色,黑色,然后让雌性只显示轮廓,并以白色为中心。

plot(year, logit.prop, type="n", xlab="Year of graduation", ylab="Logit proportion of survivors", ylim=c(-1,3))
points(year[faculty=="M"], logit.prop[faculty=="M"], pch=21, 
points(year[faculty=="A"], logit.prop[faculty=="A"], pch=21, bg="red", col="red")

This is a section of the code i'm currently using, is there a way to tell R to colour points where the x axis value (thats year here) is both female and A? 这是我当前正在使用的代码的一部分,是否有办法告诉R标记x轴值(此处为年份)既是女性又是A的色点?

As the @mr.joshuagordon said, col and other arguments to points can take vectors. 正如@ mr.joshuagordon所说, col和其他points参数可以采用向量。 Since you didn't provide data, here's something: 由于您没有提供数据,因此请注意以下几点:

df <- data.frame(x = rep(1:4, each = 2), y = rep(1:2, times = 4), faculty = rep(c("A", "M", "S", "E"), each = 2), gender = rep(c("M","F"), times = 4))
df
#   x y faculty gender
# 1 1 1       A      M
# 2 1 2       A      F
# 3 2 1       M      M
# 4 2 2       M      F
# 5 3 1       S      M
# 6 3 2       S      F
# 7 4 1       E      M
# 8 4 2       E      F
plot(y ~ x, data = df, pch = ifelse(gender == "M", 16, 21), col = factor(faculty))
text(y + 0.5 ~ x, data = df, labels = faculty)

简单点

In this case, factor(faculty) worked because factors are internally integers counting from 1 on up. 在这种情况下, factor(faculty)起作用了,因为factor是内部整数,从1开始向上计数。 You can see what colors are set for each number with: 您可以使用以下命令查看为每个数字设置的颜色:

palette()
# [1] "black"   "red"     "green3"  "blue"    "cyan"    "magenta" "yellow" 
# [8] "gray"   

If you want different colors, you can either use conditionals (such as ifelse ) on faculty itself, or you can just define the palette colors (see ?palette ). 如果您想要不同的颜色,则可以在faculty本身上使用条件(例如ifelse ),也可以仅定义调色板的颜色(请参阅?palette )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM