R中的多个散点图

时间:2014-07-28 05:39:00

标签: r function plot

我有一个稍微复杂的绘图任务。我在那里一半,很确定如何得到它。我有一个下面表格的数据集,有多个科目,每个科目在治疗组0或治疗组1中,每个科目贡献几行数据。每行对应一个时间点,在该时间点列中有值" count1,count2,weirdname3等。

任务1.我需要计算" Days",这就是每行的访问日期 - 开始日期。应该是一个应用类型函数,我想。

任务2.我必须为每个计数变量制作一个带有一个散点图的多图数字(count1的图表,count2的图表等)。在每个散点图中,我需要绘制计数值(y轴)与#34;天" (x轴)并连接每个主题的点。治疗组0中的受试者是一种颜色,治疗组1中的受试者是另一种颜色。每个散点图应根据需要标记为count1,count2等。

我正在尝试使用基本绘图功能,并采用编写绘图功能的方法稍后调用。我认为这可行,但需要一些语法帮助。

#Enter example data
tC <- textConnection("
ID  StartDate   VisitDate   Treatstarted    count1  count2  count3  Treatgroup
C0098   13-Jan-07   12-Feb-10   NA  457 343 957 0
C0098   13-Jan-06   2-Jul-10    NA  467 345 56  0
C0098   13-Jan-06   7-Oct-10    NA  420 234 435 0
C0098   13-Jan-05   3-Feb-11    NA  357 243 345 0
C0098   14-Jan-06   8-Jun-11    NA  209 567 254 0
C0098   13-Jan-06   9-Jul-11    NA  223 235 54  0
C0098   13-Jan-06   12-Oct-11   NA  309 245 642 0
C0110   13-Jan-06   23-Jun-10   30-Oct-10   629 2436    45  1
C0110   13-Jan-07   30-Sep-10   30-Oct-10   461 467 453 1
C0110   13-Jan-06   15-Feb-11   30-Oct-10   270 365 234 1
C0110   13-Jan-06   22-Jun-11   30-Oct-10   236 245 23  1
C0151   13-Jan-08   2-Feb-10    30-Oct-10   199 653 456 1
C0151   13-Jan-06   24-Mar-10   3-Apr-10    936 25  654 1
C0151   13-Jan-06   7-Jul-10    3-Apr-10    1147    254 666 1
C0151   13-Jan-06   9-Mar-11    3-Apr-10    1192    254 777 1
")
data1 <- read.table(header=TRUE, tC)
close.connection(tC)

# format date
data1$VisitDate <- with(data1,as.Date(VisitDate,format="%d-%b-%y"))

# stuck: need to define days as VisitDate - StartDate for each row of dataframe (I know I need an apply family fxn here)
data1$Days <- [applyfunction of some kind ](VisitDate,ID,function(x){x-data1$StartDate})))

# Unsure here. Need to define plot function
plot_one <- function(d){
 with(d, plot(Days, Count, t="n", tck=1, cex.main = 0.8, ylab = "", yaxt = 'n', xlab = "", xaxt="n",  xlim=c(0,1000), ylim=c(0,1200))) # set limits
    grid(lwd = 0.3, lty = 7)
    with(d[d$Treatgroup == 0,], points(Days, Count1, col = 1)) 
    with(d[d$Treatgroup == 1,], points(Days, Count1, col = 2))
}

#Create multiple plot figure
par(mfrow=c(2,2), oma = c(0.5,0.5,0.5,0.5), mar = c(0.5,0.5,0.5,0.5))
#trouble here. I need to call the column names somehow, with; plyr::d_ply(data1, ???, plot_one) 

1 个答案:

答案 0 :(得分:0)

任务1:

data1$days <- floor(as.numeric(as.POSIXlt(data1$VisitDate,format="%d-%b-%y")
                              -as.POSIXlt(data1$StartDate,format="%d-%b-%y")))

任务2:

par(mfrow=c(3,1), oma = c(2,0.5,1,0.5), mar = c(2,0.5,1,0.5))
plot(data1$days, data1$count1, col=as.factor(data1$Treatgroup), main="count1")
plot(data1$days, data1$count2, col=as.factor(data1$Treatgroup), main="count2")
plot(data1$days, data1$count3, col=as.factor(data1$Treatgroup), main="count3")