简体   繁体   中英

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

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')

在此输入图像描述

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM