用ggplot2和R创建排列图 [英] Creating a Pareto Chart with ggplot2 and R

查看:309
本文介绍了用ggplot2和R创建排列图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力如何使用ggplot2软件包在R中制作帕累托图表。在制作条形图或直方图的许多情况下,我们希望按X轴排序项目。在帕累托图中,我们希望按Y轴的值降序排列项目。有没有办法让ggplot绘制由Y轴中的值排序的项目?我试着先排序数据帧,但似乎ggplot重新排序它们。

示例:

  val < -  read.csv( (val,val [order(-Value),]))
p < - ggplot(val)
p + geom_bar(aes(State,Value,fill = variable),stat =identity,position =dodge)+ scale_fill_brewer(palette =Set1)

数据框val已排序,但输出如下所示:



alt text http://www.cerebralmastication.com/ wb-content / uploads / 2009/11 / exp.png

Hadley正确地指出,这给出了一个更好的图表来显示实际值与预测值:

  ggplot(val,aes(State,Value))+ geom_bar(stat =identity,subset =。(variable = =估计),fill =grey70)+ geom_crossbar(aes(ymin = Value,ymax = Value),subset =。(变量==actual))

返回:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/11/exp1.png



但它仍然不是帕累托图。任何提示?

解决方案

ggplot2中的横条是按照系数中的水平排序排序的。
$ b

  val $ State < -  with(val,factor(val $ State,levels = val [order(-Value),] $ State))


I have been struggling with how to make a Pareto Chart in R using the ggplot2 package. In many cases when making a bar chart or histogram we want items sorted by the X axis. In a Pareto Chart we want the items ordered descending by the value in the Y axis. Is there a way to get ggplot to plot items ordered by the value in the Y axis? I tried sorting the data frame first but it seems ggplot reorders them.

Example:

val <- read.csv("http://www.cerebralmastication.com/wp-content/uploads/2009/11/val.txt")
val<-with(val, val[order(-Value), ])
p <- ggplot(val)
p + geom_bar(aes(State, Value, fill=variable), stat = "identity", position="dodge") + scale_fill_brewer(palette = "Set1")

the data frame val is sorted but the output looks like this:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/11/exp.png

Hadley correctly pointed out that this produces a much better graphic for showing actuals vs. predicted:

ggplot(val, aes(State, Value)) + geom_bar(stat = "identity", subset = .(variable == "estimate"), fill = "grey70") + geom_crossbar(aes(ymin = Value, ymax = Value), subset = .(variable == "actual"))

which returns:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/11/exp1.png

But it's still not a Pareto Chart. Any tips?

解决方案

The bars in ggplot2 are ordered by the ordering of the levels in the factor.

val$State <- with(val, factor(val$State, levels=val[order(-Value), ]$State))

这篇关于用ggplot2和R创建排列图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆