3
votes

I would like put a bar and a line plot of two separate but related series on the same chart with a legend (the bar plot is of quarterly growth the line plot is of annual growth).

I currently do it with a data.frame in wide format and code like this:

p <- ggplot() +
    geom_bar(df, aes(x=Date, y=quarterly), colour='blue') +
    geom_line(df, aes(x=Date, y=annual), colour='red')

but I cannot work out how to add a legend, which has a red line labeled 'Annual Growth'; and a blue square labeled 'Quarterly Growth'.

Alternatively, I cannot work out how to have differnt geoms for different series with a long-form data.frame.

UPDATE:

The following example code gets me part of the way towards a solution, but with a really ugly duplicate legend. Still looking for a complete solution ... This approach is based on putting the data in long form and then plotting subsets of the data ...

library(ggplot2)
library(reshape)
library(plyr)
library(scales)

### --- make a fake data set
x <- rep(as.Date('2012-01-01'), 24) + (1:24)*30
ybar <- 1:24
yline <- ybar + 1

df <- data.frame(x=x, ybar=ybar, yline=yline)
molten <- melt(df, id.vars='x', measure.vars=c('ybar', 'yline'))
molten$line <- ifelse(molten$variable=='yline', TRUE, FALSE)
molten$bar <- ifelse(molten$variable=='ybar', TRUE, FALSE)

### --- subset the data set
df.line  <- subset(molten, line==TRUE)
df.bar   <- subset(molten, bar==TRUE)

### --- plot it
p <- ggplot() +
geom_bar(data=df.bar, mapping=aes(x=x, y=value, fill=variable, colour=variable),
    stat='identity', position='dodge') +
geom_line(data=df.line, mapping=aes(x=x, y=value, colour=variable)) +

opts(title="Test Plot", legend.position="right") 

ggsave(p, width=5, height=3, filename='plot.png', dpi=150)

And an example plot ...

enter image description here

1

1 Answers

4
votes

By use of the subset argument to geoms.

> x=1:10;df=data.frame(x=x,y=x+1,z=x+2)
> ggplot(melt(df),
    aes(x,value,color=variable,fill=variable))+
  geom_bar(subset=.(variable=="y"),stat="identity")+
  geom_line(subset=.(variable=="z"))

enter image description here