Manoj Agrawal Manoj Agrawal - 1 month ago 39
R Question

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

Answer

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