【问题标题】:How to change order of bars in barplot?如何更改条形图中的条形顺序?
【发布时间】:2019-04-14 05:20:02
【问题描述】:

我需要更改条形图中条形的顺序。默认是我不想要的字母顺序。我需要顺序是“小学”、“中学”、“高中”。

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.

【问题讨论】:

标签: r


【解决方案1】:

table 步骤之前,如果我们将“类型”列更改为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)

并绘制条形图

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)

数据

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多