R ggplot直方图条形降序 [英] R ggplot histogram bars in descending order

查看:105
本文介绍了R ggplot直方图条形降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用ggplot使直方图的条形降序显示.

I don't get how to make the bars of an histogram to appears in descending order with ggplot.

在这里我的代码带有一个每个人都可以使用的数据框:

Heres my code with a dataframe that everyone can use :

library(ggplot2)
library(scales)


chol <- read.table(url("http://assets.datacamp.com/blog_assets/chol.txt"), 
header = TRUE)
ggplot(chol) +
geom_histogram(aes(x = AGE, y = ..ncount.., fill = ..ncount..),
               breaks=seq(20, 50, by = 2),
               col="red",
               alpha = .2) +
scale_fill_gradient("Percentage", low = "green", high = "red") +
scale_y_continuous(labels = percent_format()) +
labs(title="Histogram for Age") +
labs(x="Age", y="Percentage")

我想要的直方图降序:

我试图在绘制之前对AGE列进行排序:

I tried to order the column AGE before plotting :

## set the levels in order we want
Chol <- within(Chol, 
               AGE <- factor(AGE, 
                                  levels=names(sort(table(AGE), 
                                                    decreasing=TRUE)

当我用ggplot和geom_histogram绘制AGE顺序时出现错误.

I get an error when i plot the order AGE with ggplot and geom_histogram.

推荐答案

首先,我想说的是,如果您对x轴进行改组,这可能会是一个非常令人困惑的情节.我认为大多数人会认为年龄是按升序排列的.

First I've gotta say I think this can potentially be a very confusing plot if you are shuffling the x-axis; I think most people would assume that ages are sorte in increasing order.

但是,如果这确实是您要执行的操作,那么 geom_histogram()确实对这里没有帮助.最好自己进行数据汇总,而只需使用ggplot进行绘图即可.这是为您的绘图生成数据的一种方法

But if this is really what you want to do, geom_histogram() really isn't going to help here. Better to do the data summary yourself and just use ggplot for plotting. Here's one way to generate the data for your plot

# helper function
pairjoin <- function(x) paste(head(x,-1), tail(x,-1), sep="-")
# use the base hist() function to calculate BINs
dd <- with(hist(chol$AGE, breaks=seq(10, 60, by = 5), plot=FALSE), data.frame(N=counts, age=pairjoin(breaks), PCT=counts/sum(counts)))

现在有了我们需要的数据,我们就可以绘制图了

Now with the data we need, we can draw the plot

ggplot(dd) +
geom_bar(aes(reorder(age, -PCT), PCT, fill=PCT),
    col="red", alpha = .2, stat="identity") +
scale_fill_gradient("Percentage", low = "green", high = "red") +
scale_y_continuous(labels = percent_format()) +
labs(title="Histogram for Age") +
labs(x="Age", y="Percentage")

这将绘制以下图:

这篇关于R ggplot直方图条形降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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