Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

r - Ordering bars in barplot()

I have a dataframe, and one of the variables (let's call it Q1) has several levels: "No use", "30 min", "1 hour", "2 hours", "3+ hours".

How can I plot a barplot(), where the bars are in the order of factor levels? I tried using sort(), but that doesn't do the trick.

EDIT: As requested, some sample data:

Q1
1 hour
1 hour
30 min
2 hours
3+ hours
3+ hours
3+ hours
3+ hours
2 hours
1 hour
2 hours
1 hour
30 min

I've tried:

barplot(table(sort(Q1)), main = "Q1 Answer Distribution", ylim = c(0, 250), cex.axis=0.9)

but it doesn't give me what I need.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One possibility is to create a factor version of Q1 where you specify the levels in the desired order:

df$Q1_fac <- factor(df$Q1, levels = c("30 min", "1 hour",  "2 hours", "3+ hours"))

tt <- table(df$Q1_fac)
tt
# Q1_fac
# 30 min   1 hour  2 hours 3+ hours 
#      2        4        3        4    

barplot(tt)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...