绘制颜色和形状并填充以匹配R中的多个变量

时间:2013-11-10 19:28:54

标签: r

我有以下数据框

 Op.1 Op.2 Site diet Horse ICS
 35   25    a    1     1  10
 32   31    a    1     2  10
 19   32    a    1     3  10
 17   26    a    1     4  10
 25   19    a    1     5  10
 25   17    a    1     6  10
 #... to 432 observations

我使用以下功能完成了Bland-Altman图:

 BAplot <- function(x,y,yAxisLim=c(-50,50),xlab="Average", ylab="Difference") {
   d <- ((x + y)/2)
   diff <- x - y        
   plot(diff ~ d,ylim=yAxisLim,xlim=c(0,60),xlab=xlab,ylab=ylab)
   abline(h=(mean(na.omit(diff))-c(-0.96,0,0.96)*sd(na.omit(diff))),lty=2)
 }

获得的情节很好。现在我试图根据数据$ Site(4级:0,1,2,3)给出颜色并根据数据级别设置$ ICS(6级:10,11,12,13,14,15)

我写了以下代码:

 clr   <- c("a"="red","b"="blue","c"="green","d"="yellow")[data$Site]
 shape <- c("10"="0","11"="1","12"="2","13"="3","14"="4","15"="5")[data$ICS]
 plot.ops<-BAplot(data$Op.1,data$Op.2,xlab="(Op1 vs Op 2)/2", ylab="Op1-mean of aOp1+Op2",col=clr,pch=shape)

但它给出了错误

 Error in BAplot(data$Op.1, data$Op.2, xlab = "(Op1 vs Op 2)/2", ylab = "Op1-mean of Op1+Op2",  : 
    unused arguments (col = clr, pch = shape)

我也尝试改变形状&lt; - c(10 = 0,11 = 1,12 = 2 ...)1,2,3是pch中的不同形状类型但它仍然不起作用。对于clr。也是如此。

我最终希望得到的是“网站”的不同颜色和“ICS”的不同形状。

这是非常简单的事情,但我认为可能存在一个基本的概念错误,但我被困住了。

我还会通过使用填充或清空的形状来添加饮食(2个级别)...但是直到我先将它排序后才能进入该阶段!

非常感谢, 中号

2 个答案:

答案 0 :(得分:0)

我尝试复制您的代码,问题是形状全部由NA构成。

这是因为data$ICS是数字,而不是字符串。

您可以使用它来解决问题(请注意,我从数字中删除了引号,否则数字本身将用作形状,这非常难看:

shapes <- c("10"=0,"11"=1,"12"=2,"13"=3,"14"=4,"15"=5)[as.character(data$ICS)]

或更简单

shapes <- (1:5)[data$ICS-10]

答案 1 :(得分:0)

这最终是为我所做的:

a<-ifelse(data$ICS==10,"a",ifelse(data$ICS==11,"b",ifelse(data$ICS==12,"c",ifelse(data$ICS==13,"d",ifelse(data$ICS==14,"e","f"))))) #ICS as characters
cls<-c(2,"orange",7,3,6,4) [factor(a)] #10-11-12-13-14-15: red,orange,yellow,green,purple,blue
b<-data$Site
shapes<-c(0,1,2,8)[factor(b)] #Square is RDC liv, Circle is RDC V, Triangle is RVC V, Star is RVC CCJ
BAplot <- function(x,y,yAxisLim=c(-50,50),xlab="Average", ylab="Difference",col=cls,pch=shapes) {
  d <- ((x + y)/2)
  diff <- x - y        
  plot(diff ~ d,ylim=yAxisLim,xlim=c(0,60),xlab=xlab,ylab=ylab,col=cls,pch=shapes)
  abline(h=(mean(na.omit(diff))-c(-0.96,0,0.96)*sd(na.omit(diff))),lty=2)
}
plot.ops<-BAplot(data$Op.1,data$Op.2,xlab="(Op1 vs Op 2)/2", ylab="Op1-mean of Op1+Op2",col=cls,pch=shapes)
title(main="Bland-Altman plots of Op1 vs Op2")
legend (34,53,legend=c("RDC Liver","RDC V","RVC V","RVC CCJ"), pch=c(0,1,2,8), pt.cex=2, y.intersp=0.8) #legend for shape
legend (49,53,legend=c("10th ICS","11th ICS","12th ICS","13th ICS","14th ICS","15th ICS"), pch=22, pt.cex=2, pt.bg=c(2,"orange",7,3,6,4), y.intersp=0.6) #legend for the colours

不知道为什么但是如果我写了

就不行
shapes<-c(0,1,2,8)[factor(data$Site)]

只有在我创建

时才有用
b<-data$Site
shapes<-c(0,1,2,8)[factor(b)]

无论如何,现在排序!

非常感谢, 马可