Order Bars in plotly Barchart in R (Example)

 

This article provides three examples to reorder the categories in a bar plot built with plotly in the R programming language.

The tutorial contains the following sections:

 

 

Kirby White Researcher Statistician Programmer

Note: This article was created in collaboration with Kirby White. Kirby is an organizational effectiveness consultant and researcher, who is currently pursuing a Ph.D. at the Seattle Pacific University. You can read more about Kirby here!

 

Example Data

We’ll use the state.name and state.area datasets for this example, as they are already loaded in R.

If you have not already done so, install and load the plotly package using this code: install.packages("plotly") and library(plotly).

We’ll only use the first five items from each dataset for this tutorial, and we can combine them into a data frame using this code:

states <- data.frame(State = state.name[1:5],
                     Area = state.area[1:5])

Let’s start with a basic barplot to look at the land area in each state. Note that the bars will appear in the row order of the dataset they come from:

plot_ly(
  data = states,
  x = ~State,
  y = ~Area,
  type = "bar"
)


The bar for each state has been displayed in the order they were listed in the data frame, which happens to be alphabetical.

Let’s explore other ways to order the bars!

 

Alphabetically and Reverse Alphabetically

We can customize the bar order with the layout settings of a plotly graph. Specifically, the categoryorder options.

To order the bars by their name alphabetically, we can use this code:

plot_ly(
  data = states,
  x = ~State,
  y = ~Area,
  type = "bar"
) %>% 
layout(xaxis = list(categoryorder = "category ascending"))


A slight modification to this code lets us display the bars reverse alphabetically:

plot_ly(
  data = states,
  x = ~State,
  y = ~Area,
  type = "bar"
) %>% 
layout(xaxis = list(categoryorder = "category descending"))


 

Ascending and Descending Values

To order the bars based on the values they display, we can use this code to sort them in ascending order:

plot_ly(
  data = states,
  x = ~State,
  y = ~Area,
  type = "bar"
) %>% 
layout(xaxis = list(categoryorder = "total ascending"))


A slight modification to this and we can display them in descending order:

plot_ly(
  data = states,
  x = ~State,
  y = ~Area,
  type = "bar"
) %>% 
layout(xaxis = list(categoryorder = "total descending"))


 

Custom Order

If you need to sort your bars into an order that isn’t programmatically identifiable by the methods above, you can add one more piece to the xaxis layout parameters. Set categoryorder = "array" and then use categoryarray to specify the order. You can enter a character vector directly or refer to a vector stored in another R object.

plot_ly(
  data = states,
  x = ~State,
  y = ~Area,
  type = "bar"
) %>% 
layout(xaxis = list(categoryorder = "array",
                    categoryarray = c("Arkansas", "California", "Alaska", "Alabama", "Arizona")))


 

Ordered Factors

If you’re working with categories that already have an order specified (i.e., an ordered factor), plotly will automatically display the bars in their ascending order.

Here’s a sample dataset to demonstrate this:

x <- c("Very Dissatisfied", "Dissatisfied", "Satisfied", "Very Satisfied")
 
customers <- data.frame(Satisfaction = factor(x = rev(x),
                                              levels = x,
                                              ordered = TRUE),
                        Purchases = c(17,16,8,3))

Here’s what it looks like using our custom data:

plot_ly(
  data = customers,
  x = ~Satisfaction,
  y = ~Purchases,
  type = "bar"
)


You can tell that it’s ordered by the factor meta-data because it’s different than how the rows are sorted in the data frame (which is normally the default).

Please note that altering the categoryorder settings with the methods described above will revert to an alphabetical ordering and ignore the factor ordering.

 

Further Resources

You can check out these other articles for more detailed examples and videos of these popular charts in plotly:

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top