简体   繁体   English

R:着色图

[英]R: Coloring plots

I have some data that I want to plot (eg plot(x,y) ) but I have some criteria that I want to color by depending on the values in vector z which looks like c(1, 0, 1, 1, 1, 1, 0, NA ,0 ,0, .....) etc. 我有一些要绘制的数据(例如plot(x,y) ),但我有一些根据矢量z的值进行着色的标准,看起来像c(1, 0, 1, 1, 1, 1, 0, NA ,0 ,0, .....)等。

Is there some way I can choose what color the 1 's are going to be and what color the 0 's are going to be? 有什么方法可以选择1的颜色和0的颜色?

Thanks 谢谢

I know this has already been answered but here is some very intuitive code with a plot for reference. 我知道已经回答了,但是这里有一些非常直观的代码,并提供了参考。

#Let's create some fictional data 
x = rbinom(100,1,.5)
x[round(runif(10)*100)] = NA

#Assign colors to 1's and 0's
colors = rep(NA,length(x))
colors[x==1] = "blue"
colors[x==0] = "red" 

#Plot the vector x
plot(x,bg=colors,pch=21)

在此处输入图片说明

You want to get a vector of colors as long as the x and y vectors, for example as follows: 您希望获得与xy向量一样长的颜色向量,例如,如下所示:

z[is.na(z)] = 2
zcol = c("red", "blue", "black")[z + 1]

Then you can simply do: 然后,您可以简单地执行以下操作:

plot(x, y, col=zcol)

Maybe I am missing something, but I think you want: 也许我缺少了一些东西,但是我想你想要:

plot(x,y,col=ifelse(z==0,'zerocolour','onecolour'))

where you replace the two colours with red and blue or whatever. 在这里用redblue或其他颜色替换两种颜色。

I don't think the NA will be plotted, so you don't have to worry about those. 我认为不会绘制NA ,因此您不必担心这些。

For more colours, you could create a little mapping data.frame with the unique values of z , and then merge z with the data.frame . 要获得更多颜色,可以使用z的唯一值创建一个小的映射data.frame ,然后将zdata.frame合并。 Here is an example with two colours: 这是两种颜色的示例:

map<-data.frame(z=c(0,1),col=c('red','blue'))
plot(x,y,col=merge(z,map)$col)

Using the ggplot2 package 使用ggplot2软件包

require(ggplot2)

df <- data.frame(x = c(1, 2, 3, 4, 5), y = c(2, 3, 4, 6, 7), z = c(1, 0 , 1, 0 , NA))
df$z[is.na(df$z)] = 2
ggplot(df, aes(x, y, color = as.factor(z))) + geom_point()

You can supply vector of colors to argument col= and then use z to select colors. 您可以将颜色向量提供给参数col= ,然后使用z选择颜色。 Used paste() to convert NA to character and then as.factor() to interpret those characters as 1, 2 and 3. 使用paste()将NA转换为字符,然后使用as.factor()将这些字符解释为1、2和3。

x<-c(1,2,3,4,5)
y<-c(1,2,3,4,5)
z<-c(1,0,NA,1,1)
plot(x,y,col=c("red","green",'black')[as.factor(paste(z))],pch=19,cex=3)

str(as.factor(paste(z)))
Factor w/ 3 levels "0","1","NA": 2 1 3 2 2

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

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