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

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

问题描述

我想要实现的与这里已经问过的完全相同(特别是使用 R 的基础图形,而不是像 ggplotlattice 这样的包):

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

num2 <- factor(num, labels = as.character(cat))因子错误(num,labels = as.character(cat)):无效的标签";长度 10 应该是 1 或 9

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

num <- as.factor(num)条形图(表(数量))

但这是我得到的:

因此,在我的这个特殊情况下,与那个问题略有不同,我应该如何对条形图进行排序,以便条形图由 data$num 定义,但根据 data$num 进行排序代码>data$cat?

解决方案

我得到以下内容,

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)cat <- c(字母[1:10])数据 <- data.frame(num, cat)条形图(数据[订单(数据[,1],递减=真),][,1],names.arg=数据[订单(数据[,1],递减=真),][,2])

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

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)cat <- c(字母[1:10])数据 <- data.frame(num, cat)数据 2 <- 数据[顺序(数据[,1],递减=真),]barplot(data2[,1],names.arg=data2[,2])

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)

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

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))

But here is what I got:

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?

解决方案

I get the following,

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])

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天全站免登陆