ggplot

2014-01-23 22 views
0

如何在barplot上添加線圖我有數據幀,其中有age,gender(男/女)列。我想按年齡繪製分組條形圖,並且想要追加age的男性與女性的比例線圖。ggplot

test是數據幀與agegender作爲列

ratio_df是在ggplot

ggplot(data = test, aes(x = factor(age), fill = gender)) + geom_bar() + geom_line(data = ratio_df, aes(x = age, y = ratio)) 
男性的新的數據幀存儲比女性中的每個 age

ratio_df <- ddply(test, 'age', function(x) c('ratio' = sum(test$gender == 'Male')/sum(test$gender == 'Female'))) 

ggplot與barplot和比線

+3

請給出[再現的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – ziggystar

+2

你的ddply調用似乎對我來說 - 我認爲它總是產生相同的比率(在整個數據幀中)。 – CMichael

+0

我想要帶有測試數據框的barplot和追加比率_df數據框的線條圖。 –

回答

0

如上所述,你的ddply調用似乎對我來說 - 我認爲它總是產生相同的比率(在整個數據幀中)。我從頭頂上找不到一個緊湊優雅的人,所以我不得不求助於一個有點笨重的人,但它確實有效。

編輯:我更改了代碼以反映http://rwiki.sciviews.org/doku.php?id=tips:graphics-ggplot2:aligntwoplots描述的解決方法來解決OP的評論。

#sample data 
test=data.frame(gender=c("m","m","f","m","f","f","f"),age=c(1,3,4,4,3,4,4)) 

require(plyr) 
age_N <- ddply(test, c("age","gender"), summarise, N=length(gender)) 

require(reshape2) 
ratio_df <- dcast(age_N, age ~ gender, value.var="N", fill=0) 
ratio_df$ratio <- ratio_df$m/(ratio_df$f+ratio_df$m) 

#create variables for facetting 
test$panel = rep("Distribution",length(test$gender)) 
ratio_df$panel = rep("Ratio",length(ratio_df$ratio)) 

test$panel <- factor(test$panel,levels=c("Ratio","Distribution")) 

require(ggplot2) 
g <- ggplot(data = test, aes(x = factor(age))) 
g <- g + facet_wrap(~panel,scale="free",ncol=1) 
g <- g + geom_line(data = ratio_df, aes(x = factor(age), y = ratio, group=1)) 
g <- g + geom_bar(aes(fill=gender)) 
print(g) 

這是你在找什麼?不過,我認爲@SvenHohenstein是正確的,該線沒有任何信息,因爲從填充中可以看出分割是明顯的。

enter image description here

+0

感謝您的解答。它工作正常,但我想爲線條分配正確的y軸,爲barplot分配左側的y軸。 –

+0

兩個不同的y軸在ggplot中是不可能的 - 請參閱Hadley的答案:http://stackoverflow.com/a/3101876/3124909 – CMichael

+0

請參閱編輯以獲得可能的解決方法。 – CMichael