【问题标题】:how to append line graph above barplot in ggplot如何在ggplot中的barplot上方附加折线图
【发布时间】:2014-01-24 17:05:58
【问题描述】:

我的数据框包含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))

【问题讨论】:

  • 你的 ddply 调用对我来说似乎是 - 我认为它总是产生相同的比率(在整个数据帧上)。
  • 我想要带有测试数据框的条形图和附加了 ratio_df 数据框的线图。
  • 当您创建堆叠条形图时,其中gender 由不同的fill 颜色表示,对于每个堆叠条形而言,男性与女性的比例本质上是可见的。

标签: r ggplot2


【解决方案1】:

如上所述,您的 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 是正确的,因为该行没有任何信息,因为从填充中可以明显看出拆分。

【讨论】:

  • 感谢您的解决方案。它工作正常,但我想为线条分配右 y 轴,为条形图分配左 y 轴。
  • 在 ggplot 中不可能有两个不同的 y 轴 - 请在此处查看 Hadley 的回答:stackoverflow.com/a/3101876/3124909
猜你喜欢
  • 1970-01-01
  • 2021-10-07
  • 2023-02-22
  • 2012-04-28
  • 2018-11-14
  • 1970-01-01
  • 2021-09-29
  • 2020-03-25
  • 1970-01-01
相关资源
最近更新 更多