如何更改Barplot中条形的顺序?

时间:2019-04-14 05:20:03

标签: r

我需要更改条形图中条形的顺序。默认值是我不希望使用的字母顺序。我需要顺序为“小学”,“中学”,“高中”。

colors <- c("cornflowerblue","mediumpurple1","coral2",  "azure4")
colorsleg <-c("cornflowerblue","mediumpurple1","coral2",  "azure4")
mytable <- table(century$race, century$type)
mytable2 <- prop.table(mytable, 2) #changes counts to percentages#
M <- c(
"Elementary 
School",
"High 
 School",
"Middle 
   School")

par(mar=c(5, 6, 4.1, 2.1)) #THIS CHANGES THE GRAPHS MARGINS TO MAKE
#ROOM FOR LONG Y LABELS. default margin sizes are mar=c(5.1, 4.1, 4.1, 2.1) 
#

barplot(mytable2, 
col=colors, 
border = NA, 
ylim = range(0,3),
xlim = range(0,1), 

    # #THIS GETS RID OF Y AXIS LINE#
    family="Arial", 
    horiz = T, names.arg= M,
    las=1)`
`
I need the order to Elementary School, Middle School, High School.

1 个答案:

答案 0 :(得分:2)

table步骤之前,如果我们将'{type}列更改为factor,并且将levels指定为'M'中的值

century$type <- factor(century$type, levels = M)

哪里

M <- c("Elementary School", "Middle School", "High School")

然后执行tableprop.table步骤

mytable <- table(century$race, century$type)
mytable2 <- prop.table(mytable, 2)

并绘制barplot

par(mar=c(5.5, 8.5, 5.1, 2.1))
barplot(mytable2, 
 col=colors, 
 border = NA, 
 ylim = range(0,3),
 xlim = range(0,1), 


     family="Arial", 
     horiz = TRUE, names.arg= M,
     las=1)

enter image description here

数据

century <- structure(list(race = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 1L, 
 1L, 1L, 1L), .Label = c("F", "M"), class = "factor"), type = structure(c(3L, 
 2L, 3L, 3L, 3L, 1L, 2L, 3L, 1L, 2L), .Label = c("Elementary School", 
 "High School", "Middle School"), class = "factor")),
  class = "data.frame", row.names = c(NA, -10L))