user08041991
user08041991

Reputation: 637

combining geom_ribbon when x is a factor

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...

Upvotes: 2

Views: 2933

Answers (1)

Mike H.
Mike H.

Reputation: 14360

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))

Upvotes: 5

Related Questions