Sorting bars in barplot ()

I have a data frame, and one of the variables (let it be called Q1) has several levels: "No use", "30 minutes", "1 hour", "2 hours", "3 hours".

How can I build barplot () where the bars are in order of factor levels? I tried using sort (), but that does not 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 tried:

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

but he does not give me what I need.

+2
source share
2 answers

As Henrik stated, you need to get the data into a factor (at least this is the easiest way to do this). Consider the following example with some fake data ...

 #generate 1000 random uniform integers between 1 and 5 data <- floor(runif(1000, 1,6)) #make data a factor with given labels fdata <- factor(data, labels = c("No use", "30 min", "1 hour", "2 hours", "3+ hours")) 

This can be done in the r database with a graph (barplot is not required when y is not specified)

 #in base R, just use plot - when y is missing, barplot is produced plot(fdata) 

You can also build in ggplot2

 #in ggplot2 require(ggplot2) #make a dataframe df <- data.frame(id = seq(1:length(fdata)), fdata = fdata) #plot via geom_bar ggplot(df, aes(fdata)) + geom_bar() 

Based on your initial example, in addition to specifying levels, you will need to set ordered=TRUE , as shown below. Otherwise, "No Use" will be displayed at the end of the list.

 #get data into a factor (provided data plus "No use") q1 <- c("No use" ,"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") q1f = factor(q1, levels = c("No use", "30 min", "1 hour", "2 hours", "3+ hours"), ordered=TRUE) 

Then you can apply the graph logic shown above ...

+3
source

One possibility is to create a version of the Q1 factor , where you specify 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

+3
source

All Articles