简体   繁体   English

如何在 R 中重新排列 x 轴上的条形

[英]How rearrange the bars on the x-axis in R

I am new to using R and would appreciate help on a code.我是使用 R 的新手,希望对代码有帮助。

I am attempting to re-arrange the bars on the x-axis of my plot.我正在尝试重新排列 plot 的 x 轴上的条形图。 Most sources I have seen provide ways to do this in ascending/ descending order, or alphabetically;我见过的大多数资料都提供了按升序/降序或字母顺序执行此操作的方法; or for ggplot (I need to use barplot).或用于 ggplot(我需要使用 barplot)。

My data table currently looks like this...我的数据表目前看起来像这样......

       Expected       Observed  
Avg       50             12 
Good      48             50 
Bad       77             82 
Worse     12             12

When I plot this table using the code当我plot这个表使用代码

barplot(data.table, beside=T,
        ylim=c(0,100),
        col=c("blue", "red")
legend("topright", c("Expected","Observed"), pch=15, 
       col=c("blue","red"), 
       bty="n")

The x-axis of the bars Avg, Good, Bad, Worse are arranged in alphabetical order. Avg、Good、Bad、Worse 条的 x 轴按字母顺序排列。 I am trying to re-arrange them into the order of Bad, Worse, Avg, Good.我正在尝试将它们重新排列为 Bad、Worse、Avg、Good 的顺序。 It was suggested I turn these into factors, but I am met with an error every time I ty to do so saying... "$ operator is invalid for atomic vectors" Using the code有人建议我将这些转换为因素,但每次我这样做时都会遇到一个错误...“$ operator is invalid for atomic vectors”使用代码

data.table$Expected<- as.factor(data.table$Expected)

and

data.table$Avg<- as.factor(data.table$Avg)

Using dput(head(daily)) results in:使用 dput(head(daily)) 会导致:

structure(c(275.939393939394, 292, 57.0909090909091, 47, 90.3939393939394, 
80, 47.5757575757576, 52), .Dim = c(2L, 4L), .Dimnames = list(
    c("Expected", "Observed"), c("average", "best", "better", 
    "good")))

Any way to re-arrange these with code instead of turning them to factors?有什么方法可以用代码重新排列这些而不是把它们变成因子?

Thank you!谢谢!

Thank you for the reproducible example.感谢您提供可重现的示例。 I suggest you to add this code before plotting, which will reorder the columns in your data.我建议您在绘图之前添加此代码,这将重新排列数据中的列。

The order will then be: average, good, better, best.然后顺序将是:平均、好、更好、最好。

data.frame<-data.frame[,c(1,4,3,2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM