Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 geom_area plots unexpectedly (ends in wrong place)

Tags:

r

ggplot2

I'm using ggplot2 to plot the following data using geom_area. The values are designed to be a x axis mirror image. But the end of the plot for dog is not mirrored.

enter image description here

But as you can see from this data frame dog should end on x=100 and y=0 but it seems to end on x=100 and y=100 (see last row)

How can I make dog mirror cat exactly?

       x   y animal
1  100.0 100    cat
2   90.0  89    cat
3   84.0  85    cat
4   55.5  60    cat
5   28.3  37    cat
6   27.0  32    cat
7   18.0  25    cat
8    0.0   0    cat
9    0.0 100    dog
10  10.0  89    dog
11  16.0  85    dog
12  44.5  60    dog
13  71.7  37    dog
14  73.0  32    dog
15  82.0  25    dog
16 100.0   0    dog


dat <- structure(list(x = c(100, 90, 84, 55.5, 28.3, 27, 18, 0, 0, 10, 
    16, 44.5, 71.7, 73, 82, 100), y = c(100, 89, 85, 60, 37, 32, 
    25, 0, 100, 89, 85, 60, 37, 32, 25, 0), animal = c("cat", "cat", 
    "cat", "cat", "cat", "cat", "cat", "cat", "dog", "dog", "dog", 
    "dog", "dog", "dog", "dog", "dog")), class = "data.frame", row.names = c(NA, 
    -16L), .Names = c("x", "y", "animal"))

library(ggplot2)
ggplot(dat) + theme_bw() +
    geom_area(aes(x=x, y=y, group=animal, fill=animal), alpha=.3)  

Oddly, if I subset just dog it plots correctly:

ggplot(subset(dat, animal=="dog")) + theme_bw() +
    geom_area(aes(x=x, y=y, group=animal, fill=animal), alpha=.3)  

enter image description here

like image 501
Tyler Rinker Avatar asked Nov 25 '14 20:11

Tyler Rinker


2 Answers

I get the same error... Another possible work around is to use geom_ribbon.

ggplot(dat) + theme_bw() +
geom_ribbon(aes(x = x, ymin = 0, ymax = y, group = animal, fill = animal, position = "stack"), alpha=.3)  

This also gives the right plot:

like image 83
LJW Avatar answered Oct 16 '22 00:10

LJW


I'm not sure why you get that unexpected result. I got the same strange plot.

A possible workaround:

ggplot() +
  geom_area(data=dat[dat$animal=="dog",], aes(x=x, y=y, fill="red"), alpha=.3) +
  geom_area(data=dat[dat$animal=="cat",], aes(x=x, y=y, fill="blue"), alpha=.3) +
  scale_fill_discrete("Animal",breaks=c("red","blue"),labels=c("dog","cat")) +
  theme_bw()

which gives the desired result: enter image description here

like image 37
Jaap Avatar answered Oct 16 '22 00:10

Jaap