重新排序R的barplot()中的条 [英] Re-ordering bars in R's barplot()

查看:444
本文介绍了重新排序R的barplot()中的条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的功能与此处已经要求的完全相同(特别是使用R的基本图形,而不是像ggplotlattice这样的软件包):

What I want to achieve is exactly the same that was already asked here (and specifically using R's base graphics, not packages like ggplot or lattice): Ordering bars in barplot()

但是,那里提出的解决方案似乎对我不起作用.我需要的是以下内容.假设我有这个:

However, the solutions proposed there do not seem to work for me. What I need to is the following. Suppose I have this:

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:length(num)])
data <- data.frame(num, cat)

如果我使用barplot(data$num)生成条形图,这就是我得到的:

If I generate a barplot using barplot(data$num), here is what I get:

现在,我想根据data$cat重新排列条形.按照我上面提到的链接,我尝试了接受的答案,但出现了错误:

Now, I want to reorder the bars according to data$cat. Following the link I mentioned above, I tried the accepted answer but got an error:

num2 <- factor(num, labels = as.character(cat))
Error in factor(num, labels = as.character(cat)) : invalid 'labels'; length 10 should be 1 or 9

然后我也在那里尝试了另一个答案:

Then I also tried the other answer there:

num <- as.factor(num)
barplot(table(num))

但这是我得到的:

因此,在我的特殊情况下,该问题与该问题略有不同,我应如何对小节图进行排序,使小节由data$num定义,但根据data$cat进行排序?

So, in this particular case of mine, which is slightly different from that question, how should I order the barplot so the bars are defined by data$num but ordered according to data$cat?

推荐答案

我得到以下内容

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:10])
data <- data.frame(num, cat)
barplot(data[order(data[,1],decreasing=TRUE),][,1],names.arg=data[order(data[,1],decreasing=TRUE),][,2])

上面的代码两次使用order()函数(请参见下面的注释).为避免这样做,可以将有序data.frame的结果存储在新的data.frame中,并可以将其用于生成条形图.

The above code uses the order() function twice (see comments, below). To avoid doing this the results of the ordered data.frame can be stored in a new data.frame and this can be used to generate the barplot.

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:10])
data <- data.frame(num, cat)
data2  <- data[order(data[,1],decreasing=TRUE),]
barplot(data2[,1],names.arg=data2[,2])

这篇关于重新排序R的barplot()中的条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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