首页 文章

如何在ggplot中将条形图附加到条形图上方

提问于
浏览
0

我的数据框有 agegender (男/女) . 我想根据年龄绘制分组条形图,并且想要追加每个 age 的男性与女性比例的线图 .

test 是数据框, agegender 为列

ratio_df 是每个男性与女性的新数据帧存储比率 age

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

ggplotggplot 中有条形图和比率线

ggplot(data = test, aes(x = factor(age), fill = gender)) + geom_bar() + geom_line(data = ratio_df, aes(x = age, y = ratio))

1 回答

  • 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

相关问题