Home > Mobile >  Sort barplots variables individual with base R
Sort barplots variables individual with base R

Time:01-17

I want to sort boxplot variables individually and not by quantity or alphabetically. How does this work?

I have already tried with order and sort, without success. This is the code thats works with the random order of variables

# The barplot
png(file="question1.png", width=1200, height=900)
barplot(table(example_1$Question1), main = "question1")
dev.off()

#This ist the table I have

 Question1 Qestion2
1        yes  partial
2         no      yes
3        yes      yes
4        yes      yes
5    partial       no
6        yes  partial
7    partial       no
8         no      yes
9         no       na
10        no       no
11        no  partial
12       yes       no
13       yes       na
14        na  partial
15        na  partial
16        na       na
17       yes      yes
18       yes       no
19         n       no
20         n       no

CodePudding user response:

You can subset a table object with a vector of names, this allows you to manually change the order of bars:

example_1 <- read.table(text = "
Question1 Qestion2
1        yes  partial
2         no      yes
3        yes      yes
4        yes      yes
5    partial       no
6        yes  partial
7    partial       no
8         no      yes
9         no       na
10        no       no
11        no  partial
12       yes       no
13       yes       na
14        na  partial
15        na  partial
16        na       na
17       yes      yes
18       yes       no
19         n       no
20         n       no")

counts <- table(example_1$Question1)
barplot(counts[c("partial", "yes", "no", "n", "na")], main = "Manual order")

Or if you still decide to sort by variable names or counts:

op <- par(mfrow = c(2, 2)) 
barplot(counts[sort(names(counts))], main = "Sort by names")
barplot(counts[sort(names(counts),decreasing = T)], main = "Sort by names, dscr.")
barplot(sort(counts), main = "Sort by values")
barplot(sort(counts,decreasing = T), main = "Sort by values, decr.")
par(op)

Created on 2023-01-16 with reprex v2.0.2

  • Related