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
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.
To reorder the bar graph in descending or ascending order, use the function reorder( ). There is no need to rename the data frame.
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"))
A couple things:
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.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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With