Трехфакторное построение с использованием xyplot - PullRequest
4 голосов
/ 17 апреля 2011

У меня была проблема с ggplot, которую я не могу решить, поэтому, возможно, кто-то здесь может указать причину. Извините, что я не могу загрузить свой набор данных, но описание некоторых данных можно найти ниже. Вывод ggplot показан ниже, кроме строки NO, все остальное в порядке.

> all.data<-read.table("D:/PAM/data/Rural_Recovery_Edit.csv",head=T,sep=",")
> all.data$Water<-factor(all.data$Water,labels=c("W30","W60","W90"))
> all.data$Polymer<-factor(all.data$Polymer,labels=c("PAM-0  ","PAM-10  ","PAM-40  "))
> all.data$Group<-factor(all.data$Group,labels=c("Day20","Day25","Day30"))
> dat<-data.frame(Waterconsump=all.data[,9],Water=all.data$Water,Polymer=all.data$Polymer,Age=all.data$Group)

> ggplot(dat,aes(x=Water,y=Waterconsump,colour=Polymer))+
+ stat_summary(fun.y=mean, geom="line",size=2)+
+ stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar")+#,position="dodge"
+ facet_grid(~Age)

> dim(dat)
[1] 108   4
> head(dat)
  Waterconsump Water  Polymer   Age
1         10.5   W30 PAM-10   Day20
2         10.3   W30 PAM-10   Day20
3         10.1   W30 PAM-10   Day20
4          7.7   W30 PAM-10   Day20
5          8.6   W60 PAM-10   Day20
6          8.4   W60 PAM-10   Day20
> table(dat$Water)

W30 W60 W90 
 36  36  36 
> table(dat$Polymer)

 PAM-0   PAM-10   PAM-40   
      36       36       36 
> table(dat$Age)

Day20 Day25 Day30 
   36    36    36 

The out put of the ggplot и, если я изменил geom на "bar", вывод в порядке. The ggplot output when geom=

below is the background for this Q
#

Я бы хотел построить несколько переменных, которые были подвержены одному и тому же 3 факторам. Используя xyplot, я могу построить 2 из них в пределах одной фигуры. Тем не менее, я понятия не имею, как включить третий и расположить фигуру в N вспомогательных участков (N равно номеру уровня третьего фактора). Итак, мои цели будут:

  1. Постройте 3-й фактор и разделите график на N субплотов, где N - уровни 3-го фактора.

  2. Лучше работать как функция, так как мне нужно построить несколько переменных. Ниже приведен пример с двумя факторами и мой рабочий пример для построения двух факторов.

Заранее спасибо ~

Marco

library(reshape)
library(agricolae)
library(lattice)
yr<-gl(10,3,90:99)
trt<-gl(4,75,labels=c("A","B","C","D"))

third<-gl(3,100,lables=c("T","P","Q")) ### The third factor to split the figure in to 4 subplots

dat<-cbind(runif(300),runif(300,min=1,max=10),runif(300,min=100,max=200),runif(300,min=1000,max=1500))
colnames(dat)<-paste("Item",1:4,sep="-")
fac<-factor(paste(trt,yr,sep="-"))
dataov<-aov(dat[,1]~fac)
dathsd<-sort_df(HSD.test(dataov,'fac'),'trt')
trtplt<-gl(3,10,30,labels=c("A","B","C"))
yrplt<-factor(substr(dathsd$trt,3,4))

prepanel.ci <- function(x, y, ly, uy, subscripts, ...) 
{ 
    x <- as.numeric(x) 
    ly <- as.numeric(ly[subscripts]) 
    uy <- as.numeric(uy[subscripts]) 
    list(ylim = range(y, uy, ly, finite = TRUE)) 
} 
panel.ci <- function(x, y, ly, uy, subscripts, pch = 16, ...) 
{ 
    x <- as.numeric(x) 
    y <- as.numeric(y) 
    ly <- as.numeric(ly[subscripts]) 
    uy <- as.numeric(uy[subscripts]) 
    panel.arrows(x, ly, x, uy, col = "black", 
                 length = 0.25, unit = "native", 
                 angle = 90, code = 3) 
    panel.xyplot(x, y, pch = pch, ...) 
} 

xyplot(dathsd$means~yrplt,group=trtplt,type=list("l","p"),
        ly=dathsd$means-dathsd$std.err,
        uy=dathsd$means+dathsd$std.err,
        prepanel = prepanel.ci, 
        panel = panel.superpose, 
        panel.groups = panel.ci 
        )

This is the figure I would like mydata to be! Using Deepayan's solution, I am able to add the error bar like this based on 2 factors

Ответы [ 2 ]

7 голосов
/ 17 апреля 2011

Вот еще один способ сделать это, используя магию ggplot.Поскольку ggplot будет рассчитывать для вас сводные данные, я подозреваю, что это означает, что вы можете пропустить весь шаг выполнения aov.

Ключ в том, что ваши данные должны быть в единственном data.frame, который вы можете передать ggplot.Обратите внимание, что я создал новые демонстрационные данные для демонстрации.

library(ggplot2)

df <- data.frame(
  value = runif(300),
  yr = rep(1:10, each=3),
  trt = rep(LETTERS[1:4], each=75),
  third = rep(c("T", "P", "Q"), each=100)
)

ggplot(df, aes(x=yr, y=value, colour=trt)) + 
  stat_summary(fun.y=mean, geom="line", size=2) +
  stat_summary(fun.ymin=min, fun.ymax=max, geom="errorbar") +
  facet_grid(~third)

enter image description here

Вы можете пойти еще дальше и создать фасеты в двух измерениях:

ggplot(df, aes(x=yr, y=value, colour=trt)) + 
  stat_summary(fun.y=mean, geom="line", size=2) +
  stat_summary(fun.ymin=min, fun.ymax=max, geom="errorbar") +
  facet_grid(trt~third)

enter image description here

2 голосов
/ 17 апреля 2011

Это довольно близко, но я забываю, как закрасить линии ошибок, используя переменную group в Lattice, и книга Дипаяна работает.

## format a new data structure with all variables we want
dat <- data.frame(dathsd[, c(2,5)], treat = trtplt, yrplt = yrplt,
                  upr = dathsd$means + 2 * dathsd$std.err,
                  lwr = dathsd$means - 2 * dathsd$std.err)
## compute ylims
ylims <- range(dat$lwr, dat$upr)
ylims <- ylims + (c(-1,1) * (0.05 * diff(ylims)))
## plot
xyplot(means ~ yrplt, data = dat, group = treat, lwr = dat$lwr, upr = dat$upr,
       type = c("p","l"), ylim = ylims,
       panel = function(x, y, lwr, upr, ...) {
           panel.arrows(x0 = x, y0 = lwr, x1 = x, y1 = upr,
                        angle = 90, code = 3, length = 0.05)
           panel.xyplot(x, y, ...)
       })

И производит:

xyplot with error bars

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...