Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plotly barplot, sort by value

I have a barplot with categories on X axis and counts on Y. Is there a way to sort the bars in descending order on values of Y?

this is the sample code

Animals <- c("giraffes", "orangutans", "monkeys")
Count <- c(20, 14, 23)
data <- data.frame(Animals, Count)

data <- arrange(data,desc(Count))

plot_ly(data, x = ~Animals, y = ~Count, type = 'bar', name = 'SF Zoo')

Despite of arranging the data by count before the plot, I still get bars sorted alphabetically by animal names.

thanks, Manoj

like image 627
Manoj Agrawal Avatar asked Oct 24 '16 18:10

Manoj Agrawal


People also ask

How do you sort a Plotly bar graph?

In Plotly. express, we can sort a bar plot using the update_layout() function and the xaxis and yaxis parameters. In our example, we wish to sort the data based on the salary starting with the smallest to the highest salary. Hence, we need to use the xaxis parameter.

How do you arrange bars in ascending order in R?

To reorder the bar graph in descending or ascending order, use the function reorder( ). There is no need to rename the data frame.


2 Answers

to sort the bars descending by their value, you need to use a layout attribute of xaxis like so:

plot_ly(data, x = ~Animals, y = ~Count, type = 'bar', name = 'SF Zoo') %>% 
  layout(xaxis = list(categoryorder = "total descending"))
like image 162
phillyooo Avatar answered Sep 20 '22 11:09

phillyooo


A couple things:

  1. Look at str(data), your Animals character vector is coerced to a factor unless you specify stringsAsFactors = FALSE in your call to data.frame. The levels of this factor are alphabetic by default.
  2. Even if Animals is made to be a character vector in data, plot_ly doesn't know what to do with character variables and so will coerce them to factors.

You need to set factor level order to get the descending order you are looking for.

Animals <- c("giraffes", "orangutans", "monkeys")
Count <- c(20, 14, 23)
data <- data.frame(Animals, Count, stringsAsFactors = FALSE)
data$Animals <- factor(data$Animals, levels = unique(data$Animals)[order(data$Count, decreasing = TRUE)])
plot_ly(data, x = ~Animals, y = ~Count, type = "bar", name = 'SF Zoo')

enter image description here

like image 37
Jeff Keller Avatar answered Sep 22 '22 11:09

Jeff Keller