5

I am trying to plot multiple line charts with a ribbon in ggplot2. The following code gives me a black ribbon around the colored line, whereas I actually I want the ribbon to have the same color as the line.

ggplot(newdf,aes(x=date,y=value,group=variable,color=variable)) + 
  geom_line() + 
  facet_grid(variable ~.) +
  scale_x_date() +
  geom_ribbon(aes(ymin=0, ymax=value)) +
  theme(legend.position='none') +
  geom_line(aes(y=0),linetype="dotted")

This gives me a black ribbon as in the image below enter image description here

I was thinking of setting fill = variable as per below:

ggplot(newdf,aes(x=date,y=value,group=variable,color=variable)) + 
  geom_line() + 
  facet_grid(variable ~.) +
  scale_x_date() +
  geom_ribbon(aes(ymin=0, ymax=value), fill = variable) +
  theme(legend.position='none') +
  geom_line(aes(y=0),linetype="dotted")

However, this gives me the following error:

Error in do.call("layer", list(mapping = mapping, data = data, stat = stat, : object 'variable' not found

The newdf is a data.frame and looks like this

>head(newdf)
    date     variable      value
1 2014-01-02    CHINA -0.3163197
2 2014-01-03    CHINA -0.2820751
3 2014-01-06    CHINA -0.3256087
4 2014-01-07    CHINA -0.3741991
5 2014-01-08    CHINA -0.4064004
6 2014-01-09    CHINA -0.3630387

How do I color the ribbon correctly?

Saagar Elias Jacky
  • 2,684
  • 2
  • 14
  • 28
vtroost
  • 95
  • 1
  • 7
  • 8
    Put your `fill=` in the `aes()`: `geom_ribbon(aes(ymin=0, ymax=value, fill = variable))`. If that doesn't work, please make a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data so we can actually run the code. – MrFlick Apr 23 '15 at 17:18

1 Answers1

0

This should work. An example with nycflights13.

library(data.table)
library(ggplot)

dt = nycflights13::flights
setDT(dt)

# Plots first 500 values only
ggplot(dt[1:500],
aes(x=time_hour,y=dep_delay,ymin=0,ymax=dep_delay,color=origin,fill=origin)) +
    geom_line(linetype="dotted") + 
    facet_grid(vars(origin)) +
    geom_ribbon() +
    theme(legend.position='none')
Lucas
  • 91
  • 1
  • 5