Bar and line chart in one diagram with a legend under ggplot2

I would set the bar and line chart of two separate but connected series on the same chart with the legend (line chart of quarterly growth of the linear chart of annual growth).

I am currently doing this using data.frame in a 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 can’t figure out how to add a legend that has a red line that says “Annual growth”; and a blue square that says Quarterly Growth.

As an alternative, I can't figure out how to have different geometries for different series with a long data.frame format.

UPDATE:

The following code example gives me part of the solution path, but with a really ugly duplicate legend. Still looking for a complete solution ... This approach is based on putting the data in a long form and then building 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

+3
source share
1 answer

Using an argument subsetfor geometers.

> 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

+4
source

All Articles