2013-03-21 43 views
2

我有一個分組的數據,如下所示:情節分組數據

group x y 
group1 0 5 
group4 0 5 
group1 7 5 
group4 0 5 
group5 7 5 
group1 7 5 
group1 0 6 
group2 0 6 
group4 0 5 
group2 0 5 
group3 7 5 

x和y是具有範圍離散值0 7之間,我想獲得的曲線圖的地方在xy每組數據平面根據它們各自的x和y值。例如,我可以有多個group1點,所有這些點應該共享相同的顏色。如何在R中做到這一點?

回答

2

數據:

dat <- read.table(text = "group x y 
group1 0 5 
group4 0 5 
group1 7 5 
group4 0 5 
group5 7 5 
group1 7 5 
group1 0 6 
group2 0 6 
group4 0 5 
group2 0 5 
group3 7 5", header = TRUE) 

您可以使用優秀的ggplot2包方便繪圖:

library(ggplot2) 
ggplot(dat, aes(x = x, y = y, colour = group)) + 
    geom_point() + 
    facet_wrap(~ group) 

在這裏,我用facet_wrap創建爲每個組方面。原則上這是不必要的,因爲這些團體的觀點可以通過它們的顏色來區分。但在這種情況下,圖中只有三個不同的位置。因此,如果數據繪製在單個散點圖中,並非所有點都可見。

enter image description here

3

從埃裏克森的回答中的數據,你也可以看看格子包,應該已經與R安裝過程中安裝:

library(lattice) 
# Each group in a separate mini plot 
xyplot(y ~ x | group, data = dat) 
# All groups in one plot, different colors for each group 
# Not at all interesting with the example data you've provided 
xyplot(y ~ x, groups=dat$group, data = dat) 

這裏的每一個小的例子位更多的數據:

set.seed(1) 
mydf <- data.frame(
    group = sample(letters[1:4], 50, replace = TRUE), 
    x = runif(50, 0, 7), 
    y = runif(50, 0, 7) 
) 
xyplot(y ~ x, groups=mydf$group, data = mydf, 
     auto.key = list(corner = c(0, .98)), cex = 1.5) 

enter image description here

xyplot(y ~ x | group, data = mydf, 
     auto.key = list(corner = c(0, .98)), cex = 1.5) 

enter image description here

0
dd<- read.table("put the path to the txt file containing the data here", header=TRUE) 
g <- ggplot(dd, aes(as.factor(group))) 
g <- g + geom_point(aes(y=x), colour="red") 
g <- g + geom_point(aes(y=y), colour="green") 
g 

這將使您x和y作爲組的函數,在一個單一的情節,如下所示。 plotting variables as function of group