2

When doing a ggplot with geom_area, the negative y-range contains some holes as in the example below.

Example geom_area holes in the negative y range

I also got to code a very simple reproducible example, that illustrates this phenomenon:

require(ggplot2)
require(data.table)

data <- data.table(index = c(0, 1), 
                   x1 = c(-1, -1.5), 
                   x2 = c(-1, 0), 
                   x3 = c(0, -1))
mdt <- melt(data, id.vars = "index")

print(data)
#    index   x1 x2 x3
# 1:     0 -1.0 -1  0
# 2:     1 -1.5  0 -1

# Negative range: Holes
ggplot(data=mdt, aes(x=index, y=value, fill=variable)) +
  geom_area(position="stack")

# Positive range: No holes
ggplot(data=mdt, aes(x=index, y=abs(value), fill=variable)) +
  geom_area(position="stack")

Negative Range:

Toy example: holes in the negative y-range

Positive Range:

Toy example: no holes in the positive y-range

As you can see in the first plot a hole appears because x2 goes from -1 to zero and x3 from 0 to -1 at the same time. Interestingly, this weird behavior only seems to happen in the negative y-range while in the second plot there are no holes anymore.

Do you have any idea, why this happens in the negative y-range but not in the positive y-range? And any idea how to fix the problem for the negative y-range?

Thank you very much in advance!

Pablo
  • 21
  • 2

1 Answers1

0

As pointed out

here

by smouksassi, geom_area may consider 0 a positive number. This may explain the weird behavior. Also proposed by smouksassi, a quick & dirty workaround would be to set the 0's to a very small negative value as showed below:

library(ggplot2)
library(data.table)

data <- data.table(index = c(0, 1),
                   x1 = c(-1, -1.5),
                   x2 = c(-1, -1e-36), # <- Changed!
                   x3 = c(-1e-36, -1)) # <- Changed!
mdt <- melt(data, id.vars = "index")

print(data)
#>    index   x1     x2     x3
#> 1:     0 -1.0 -1e+00 -1e-36
#> 2:     1 -1.5 -1e-36 -1e+00

# Negative range: No holes anymore
ggplot(data = mdt) +
  geom_area(aes(x = index, y = value, fill = variable), position = "stack")

Created on 2018-08-04 by the reprex package (v0.2.0).

Pablo
  • 21
  • 2