plot grouped data in R

63,477

Solution 1

The data:

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)

You can use the excellent ggplot2 package for easy plotting:

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

Here, I used facet_wrap to create facets for each group. In principle this is not necessary, since the groups' points can be distinguished by their colour. But in this case there are only three different locations at the figure. Hence, not all points would be visible if the data were plotted in a single scatterplot.

enter image description here

Solution 2

Using the data from Sven's answer, you can also look at the lattice package, which should already be installed with your R installation:

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)

Here's an example of each with a little bit more data:

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

Share:
63,477
user297850
Author by

user297850

Updated on March 23, 2020

Comments

  • user297850
    user297850 about 4 years

    I have a grouped data as follows:

    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
    

    both x and y are discrete values having ranging between 0 and 7. I want to get a plot place each group data on the x-y plane according to their respective x and y values.For example, I can have multiple group1 points, all of which should share the same color. How to do that in R?