2012-09-06 109 views
3

我想在同一个图表上添加一个条形图和一个图例(棒图是季度增长的线图是的年增长)。在ggplot2下有图例的条形图和线条图

我现在做的,像这样在宽格式和代码data.frame:

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

,但我不能工作了如何添加一个传奇,其上有标注为“年度增长”红线;和一个被称为“季度增长”的蓝色方块。

另外,我不能解决如何使用长形式的data.frame为不同的系列创建不同的geoms。

UPDATE:

下面的示例代码让我的争取解决方式的一部分,而是一个真正丑陋的重复传奇。还在寻找一个完整的解决方案...这方法是基于将在长表中的数据,然后绘制数据子集...

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) 

和实例的情节......

enter image description here

回答

4

通过使用subset参数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

+0

子似乎不再在ggplot命令的工作 - 有没有解决? – ricardo

+0

你能举个例子吗? –

+0

@ alexBrown,当然 - 你的错误产生的错误'使用作为ID变量 错误在do.call(“层”,列表(映射=映射,数据=数据,统计= stat,: 找不到函数“)。 ' – ricardo