Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes this ggplot2 facet bug?

Tags:

plot

r

ggplot2

I'm working on putting together a few R demos to demonstrate some of its features to colleagues. I particularly want to get them interested in ggplot2 and so was putting together a simple example of faceting using facet_grid with the iris dataset.

To show them the different modes I wanted to show them what would be produced using .~Species, Species~. and Species~Species (a poor example I admit).

This seems to elicit some strange behaviour in ggplot and I was wondering why that might be. I would expect the plot below to contain points along the diagonal where the species names on each axis match one another. Instead everything is listed under setosa on the x-axis and then under its actual species in the y-axis.

I realise this example wouldn't arise in any realistic usage scenario, it just struck me as an interesting quirk. Why does ggplot behave like this?

I've also tried this with the mtcars dataset and get the same effect.

library("ggplot2")
data(iris)
ggplot(iris, aes(Petal.Width, Petal.Length, colour=Species)) +
  geom_point() +
  theme_bw() +
  facet_grid(Species~Species)

ggplot faceted scatterplot showing bug

like image 852
Tumbledown Avatar asked Nov 17 '15 17:11

Tumbledown


1 Answers

That's because you don't have any information for ggplot2 to print a combination of, e.g. setosa and versicolor.

Here in this code, I reuse @Sam comment and I sample (change the order) of the new column species that we are creating. This create a combinaison of species. Ecologically, it's probably misleading to do this, like I did, but for sure, it prints species in the combinaisons of the different facet_grid.

library("ggplot2")
data(iris)
iris$Species1 <- sample(iris$Species)
ggplot(iris, aes(Petal.Width, Petal.Length, colour=Species)) +
  geom_point() +
  theme_bw() +
  facet_grid(Species~Species1)

This is what it could look like. Again, I just created different pairs of species to print pairs in the facet grid. R_output

This would be an example with different years

iris$Year <- rep(2010:2014,dim(iris)[2])
ggplot(iris, aes(Petal.Width, Petal.Length, colour=Species)) +
  geom_point() +
  theme_bw() +
  facet_grid(Year~Species) 

enter image description here

like image 171
M. Beausoleil Avatar answered Oct 22 '22 12:10

M. Beausoleil