【问题标题】:How to better create stacked bar graphs with multiple variables from ggplot2?如何更好地从 ggplot2 创建具有多个变量的堆叠条形图?
【发布时间】:2010-04-05 14:46:15
【问题描述】:

我经常需要制作堆叠条形图来比较变量,而且因为我在 R 中进行所有统计,所以我更喜欢在 R 中使用 ggplot2 来完成我的所有图形。我想学习如何做两件事:

首先,我希望能够为每个变量添加适当的百分比刻度线,而不是按计数添加刻度线。计数会令人困惑,这就是我完全取出轴标签的原因。

其次,必须有一种更简单的方法来重组我的数据才能实现这一点。这似乎是我应该能够在 ggplot2 中使用 plyR 本地完成的事情,但是 plyR 的文档不是很清楚(我已经阅读了 ggplot2 书和在线 plyR 文档。

我最好的图表如下所示,创建它的代码如下:

我用来获取它的 R 代码如下:

library(epicalc)  

### recode the variables to factors ###
recode(c(int_newcoun, int_newneigh, int_neweur, int_newusa, int_neweco, int_newit, int_newen, int_newsp, int_newhr, int_newlit, int_newent, int_newrel, int_newhth, int_bapo, int_wopo, int_eupo, int_educ), c(1,2,3,4,5,6,7,8,9, NA), 
c('Very Interested','Somewhat Interested','Not Very Interested','Not At All interested',NA,NA,NA,NA,NA,NA))

### Combine recoded variables to a common vector
Interest1<-c(int_newcoun, int_newneigh, int_neweur, int_newusa, int_neweco, int_newit, int_newen, int_newsp, int_newhr, int_newlit, int_newent, int_newrel, int_newhth, int_bapo, int_wopo, int_eupo, int_educ)


### Create a second vector to label the first vector by original variable ###  
a1<-rep("News about Bangladesh", length(int_newcoun))
a2<-rep("Neighboring Countries", length(int_newneigh))
[...]
a17<-rep("Education", length(int_educ))


Interest2<-c(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17)

### Create a Weighting vector of the proper length ###
Interest.weight<-rep(weight, 17)

### Make and save a new data frame from the three vectors ###
Interest.df<-cbind(Interest1, Interest2, Interest.weight)
Interest.df<-as.data.frame(Interest.df)

write.csv(Interest.df, 'C:\\Documents and Settings\\[name]\\Desktop\\Sweave\\InterestBangladesh.csv')

### Sort the factor levels to display properly ###

Interest.df$Interest1<-relevel(Interest$Interest1, ref='Not Very Interested')
Interest.df$Interest1<-relevel(Interest$Interest1, ref='Somewhat Interested')
Interest.df$Interest1<-relevel(Interest$Interest1, ref='Very Interested')

Interest.df$Interest2<-relevel(Interest$Interest2, ref='News about Bangladesh')
Interest.df$Interest2<-relevel(Interest$Interest2, ref='Education')
[...]
Interest.df$Interest2<-relevel(Interest$Interest2, ref='European Politics')

detach(Interest)
attach(Interest)

### Finally create the graph in ggplot2 ###

library(ggplot2)
p<-ggplot(Interest, aes(Interest2, ..count..))
p<-p+geom_bar((aes(weight=Interest.weight, fill=Interest1)))
p<-p+coord_flip()
p<-p+scale_y_continuous("", breaks=NA)
p<-p+scale_fill_manual(value = rev(brewer.pal(5, "Purples")))
p
update_labels(p, list(fill='', x='', y=''))

我非常感谢任何提示、技巧或提示。

【问题讨论】:

  • 您可以多次使用factorlabels 参数来代替relevel。您还可以查看reorder,它可以按某个变量对您的级别进行排序(“非常感兴趣”的百分比?)
  • 漂亮的颜色 - 我想有一天我会用 brewer Purples 我自己 :-)
  • 您是否想要一个工作流程来生成进入类似图表的数据,并且能够在每个条形图的每个填充分组顶部添加百分比值?
  • 理想情况下,工作流程会同时产生两者。

标签: r graphics ggplot2 plyr


【解决方案1】:

你的第二个问题可以通过 reshape 包中的 melt 和 cast 来解决

在你调用 data.frame 中的元素后,你可以使用类似的东西:

install.packages("reshape")
library(reshape)

x <- melt(your.df, c()) ## Assume you have some kind of data.frame of all factors
x <- na.omit(x) ## Be careful, sometimes removing NA can mess with your frequency calculations

x <- cast(x, variable + value ~., length)
colnames(x) <- c("variable","value","freq")
## Presto!
ggplot(x, aes(variable, freq, fill = value)) + geom_bar(position = "fill") + coord_flip() + scale_y_continuous("", formatter="percent")

顺便说一句,我喜欢使用 grep 从杂乱的导入中提取列。例如:

x <- your.df[,grep("int.",df)] ## pulls all columns starting with "int_"

当您不必键入 c(' ', ...) 一百万次时,因式分解会更容易。

for(x in 1:ncol(x)) { 
df[,x] <- factor(df[,x], labels = strsplit('
Very Interested
Somewhat Interested
Not Very Interested
Not At All interested
NA
NA
NA
NA
NA
NA
', '\n')[[1]][-1]
}

【讨论】:

    【解决方案2】:

    您不需要 prop.tables 或 count 等来完成 100% 堆叠的条形图。你只需要+geom_bar(position="stack")

    【讨论】:

      【解决方案3】:

      关于..count.. 的百分比,试试:

      ggplot(mtcars, aes(factor(cyl), prop.table(..count..) * 100)) + geom_bar()
      

      但由于将函数推入 aes() 不是一个好主意,因此您可以编写自定义函数以从 ..count.. 创建百分比,将其四舍五入为 n 小数等。

      你用plyr 标记了这篇文章,但我没有看到任何plyr 在这里起作用,我敢打赌ddply() 可以完成这项工作。在线plyr 文档就足够了。

      【讨论】:

        【解决方案4】:

        如果我对您的理解正确,要解决轴标记问题,请进行以下更改:

        # p<-ggplot(Interest, aes(Interest2, ..count..))
        p<-ggplot(Interest, aes(Interest2, ..density..))
        

        至于第二个,我认为您最好使用reshape package。您可以使用它非常轻松地将数据聚合到组中。

        参考下面 aL3xa 的评论...

        library(ggplot2)
        r<-rnorm(1000)
        d<-as.data.frame(cbind(r,1:1000))
        ggplot(d,aes(r,..density..))+geom_bar()
        

        返回...

        alt text http://www.drewconway.com/zia/wp-content/uploads/2010/04/density.png

        垃圾箱现在是密度...

        【讨论】:

        • 你试过你的语法吗?您省略了geom_bar 层...但是,如果您通过..density..geom_bar,您将获得几个相同大小的条形图。请尝试添加geom_bar() 看看会发生什么。
        • 它适用于连续变量,但会产生带有因子和字符向量的全长条,大概是因为密度计算不知道如何处理非连续 x。将r 替换为f &lt;- sample(c("Agree", "No opinion", "Disagree"), size = 1000, replace = TRUE, prob = c(.2, .5, .3))。我之前遇到过很多次,因为我喜欢密度直方图,也喜欢 ggplot,但我还没有找到让它表现的方法(尽管我也没有很努力地尝试过)。
        • ...呃,刚刚想起一件事。它不起作用的原因是基于密度的直方图使用条形的面积,因此需要数字 x 和 y 轴。
        【解决方案5】:

        您的第一个问题:这有帮助吗?

        geom_bar(aes(y=..count../sum(..count..)))
        

        你的第二个问题;您可以使用重新排序来对条形进行排序吗?像

        aes(reorder(Interest, Value, mean), Value)
        

        (刚从七个小时的车程回来 - 很累 - 但我想应该可以)

        【讨论】:

        • 对不起 - 我以为你有一个融化的数据框。
        猜你喜欢
        • 2011-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-31
        • 2018-01-07
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多