如何在r

时间:2017-04-14 04:02:33

标签: r

我的代码正在读取一个如下所示的文件:

Wafer Analyses	
%HN20396815	150.000000	03/27/2016 04:06:27
Vf2	Site
2.76	1
2.32	2
2.56	3
2.45	2
2.76	4
2.98	3
2.58	1
2.42	2
2.76	1
2.32	4
2.56	3
2.45	2
2.76	4
2.98	3
2.58	1
2.42	2

然后我将“Vf2”数据按“站点”隔离,并在直方图中绘制每个站点,但直方图不打印出来,我该如何纠正?这是我的代码>

blufile <- read.table("C:/blufiles/WFRHN20396815_700.blu", skip = 2, header = TRUE, sep="\t")
Vf2 = blufile["Vf2"]
Site = blufile["Site"]
blufile2 <- data.frame(Vf2, Site)
blufile2$Vf2[blufile2$Site == '2']

set.seed(42)
p1 <- blufile2$Vf2[blufile2$Site == '1']                     # centered at 4
p2 <- blufile2$Vf2[blufile2$Site == '2']                     # centered at 6
p3 <- blufile2$Vf2[blufile2$Site == '3']                     # centered at 4
p4 <- blufile2$Vf2[blufile2$Site == '4']                     # centered at 6

plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,4))  # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,4), add=T)  # second
plot( p3, col=rgb(0,1,0,1/4), xlim=c(0,4), add=T)  # first histogram
plot( p4, col=rgb(1,1,0,1/4), xlim=c(0,4), add=T)  # second

我想要一个类似的输出 - &gt; enter image description here

1 个答案:

答案 0 :(得分:0)

解决方案@alistaire提供了您提供的数据。

ggplot(df, aes(x=Vf2)) + 
     geom_histogram(bins=5) + 
     facet_wrap(~Site)

enter image description here

在这种情况下使用的数据df是:

structure(list(Vf2 = c(2.76, 2.32, 2.56, 2.45, 2.76, 2.98, 2.58, 
2.42, 2.76, 2.32, 2.56, 2.45, 2.76, 2.98, 2.58, 2.42), Site = c(1L, 
2L, 3L, 2L, 4L, 3L, 1L, 2L, 1L, 4L, 3L, 2L, 4L, 3L, 1L, 2L)), .Names = c("Vf2", 
"Site"), class = "data.frame", row.names = c(NA, -16L)) 

如果仍然无效,请详细说明您的问题。

编辑:

您的代码存在的问题是您使用的plot会产生x,y点图,而不是hist

以下是基础解决方案:

df_list <- split(df, df$Site) #produce a list of 4 data.frame, each with one level of Site

dev.off() # close existing output on console
for(i in 1:length(df_list)){ 
   dat <- df_list[[i]]$Vf2 # select Vf2 data from site i
   hist_col <- c(rgb(0,0,1,1/4), rgb(1,0,0,1/4), rgb(0,1,0,1/4), rgb(1,1,0,1/4))[i] # select rgb colour for site i plot
   hist(dat, col=hist_col, xlim=c(0,4), ylim=c(0, 5)) #plot histogram for each site
   par(new=T) # add new histogram layer on top 

}

enter image description here

ggplot的解决方案在这种情况下稍微有些混乱:

ggplot(data=df, aes(x=Vf2, fill=factor(Site), colour=factor(Site))) +
     geom_histogram(data=df %>% filter(Site==1), bins=5, alpha=.5) + 
     geom_histogram(data=df %>% filter(Site==2), bins=5, alpha=.5) +
     geom_histogram(data=df %>% filter(Site==3), bins=5, alpha=.5) + 
     geom_histogram(data=df %>% filter(Site==4), bins=5, alpha=.5) +
     theme_bw()

enter image description here