如何改变条形图中的条形顺序?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何改变条形图中的条形顺序?相关的知识,希望对你有一定的参考价值。
我需要改变条形图中条形的顺序。默认为字母,我不想要。我需要命令是“小学”,“中学”,“高中”。
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.
答案
在table
步骤之前,如果我们将'type'列更改为factor
,并将levels
指定为'M'中的值
century$type <- factor(century$type, levels = M)
哪里,
M <- c("Elementary School", "Middle School", "High School")
然后做table
和prop.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)
data
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))
以上是关于如何改变条形图中的条形顺序?的主要内容,如果未能解决你的问题,请参考以下文章