1

Leading on from this question.

I cannot generate the shaded area when my x is a factor. Here is some sample data

time <- as.factor(c('A','B','C','D'))
x <- c(1.00,1.03,1.03,1.06)
x.upper <- c(0.91,0.92,0.95,0.90)
x.lower <- c(1.11,1.13,1.17,1.13)

df <- data.frame(time, x, x.upper, x.lower)

ggplot(data = df,aes(time,x))+
  geom_ribbon(aes(x=time, ymax=x.upper, ymin=x.lower), fill="pink", alpha=.5) +
  geom_point()

when i substitute factor into the aes() I still cannot get the shaded region. Or if i try this:

ggplot()+
  geom_ribbon(data = df, aes(x=time, ymax=x.upper, ymin=x.lower), fill="pink", alpha=.5) +
  geom_point(data = df, aes(time,x))

I still cannot get the shading. Any ideas how to overcome this...

Community
  • 1
  • 1
user08041991
  • 617
  • 8
  • 20
  • I believe `geom_ribbon` works for continuous x values only. A work around would be to treat the factor as continuous (`as.numeric(time)`) and then change the breaks/labels of the x axis using `scale_x_continuous`. – aosmith Mar 24 '16 at 19:26
  • Can you suggest as a Solution,please – user08041991 Mar 24 '16 at 19:27

1 Answers1

4

I think aosmith was exactly right, you simply need to convert your factor variable to numeric. I think the following code is what you're looking for:

ggplot(data = df,aes(as.numeric(time),x))+
  geom_ribbon(aes(x=as.numeric(time), ymax=x.upper, ymin=x.lower),     
  fill="pink", alpha=.5) +
  geom_point()

Which produces this plot:

enter image description here

EDIT EDIT: Change x-axis labels back to their original values taken from @aosmith in the comments below:

ggplot(data = df,aes(as.numeric(time),x))+
  geom_ribbon(aes(x=as.numeric(time), ymax=x.upper, ymin=x.lower),     
  fill="pink", alpha=.5) +
  geom_point() + labs(title="My ribbon plot",x="Time",y="Value") +
  scale_x_continuous(breaks = 1:4, labels = levels(df$time))
Mike H.
  • 13,960
  • 2
  • 29
  • 39
  • 2
    I think maybe the OP was asking for the axis tick labels. Something like `scale_x_continuous(breaks = 1:4, labels = levels(df$time))` – aosmith Mar 24 '16 at 20:07