2012-09-06 163 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