R plotly barplot, sort by value
bar-chart, plotly, r
Solution
A couple things:
- 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.
- 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')
Problem
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