Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot grouped data in R

Tags:

graph

plot

r

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?

like image 445
user297850 Avatar asked Sep 14 '25 07:09

user297850


1 Answers

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

like image 77
Sven Hohenstein Avatar answered Sep 16 '25 23:09

Sven Hohenstein