问题描述
我一直在努力研究如何使用 ggplot2 包在 R 中制作
但它仍然不是帕累托图.有什么提示吗?
ggplot2 中的条形按因子中的级别排序.
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:
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:
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 创建帕累托图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!