0

Problem

My question is very simple, but apparently unanswered. I have a count barplot and I simply want to order the bars based on their count. However 1. I don't want to modify the original dataframe, that is unnecessary, and in more complicated examples it would be way too long to do. 2. I don't want to change the order without changing the actual underlying order of the labels. In the MWE below, for instance, I dont want to change the genres that artists belong to (which is what literally every other answer on StackOverflow suggests to do).

Minimal Working Example

library(ggplot2)
# Create data
df <- data.frame(genre=c("Pop", "HipHop", "Latin", "Pop", "Pop", "HipHop"), artist=c("ArianaGrande", "ChrisBrown", "DaddyYankee", "EdSheeran", "LewisCapaldi", "ShawnMendes"))
# Plot
ggplot(data=df) +
  geom_bar(aes(x=genre, fill=artist))

plot

How do I order the bars, keeping everything else the same? Surely this should happen at the plot level, not at the dataframe level, nor at the "input" level of ggplot.

camille
  • 16,432
  • 18
  • 38
  • 60
Euler_Salter
  • 3,271
  • 8
  • 33
  • 74
  • I've already tried something like `newdf <- within(d, genre <- factor(genre, levels=names(sort(table(genre), decreasing=TRUE))))` and then using `newdf` instead of `df`. However, this works at the dataframe level. Surely this is unnecessary? – Euler_Salter Dec 27 '19 at 18:31
  • Are you looking for something like `geom_bar(aes(x= forcats::fct_infreq(genre), fill=artist))`? This technically manually changes the factor levels n the underlying data but skips the step of doing this outside the plotting step. – aosmith Dec 27 '19 at 18:34
  • "I dont want to change the genres that artists belong to" I don't know what you mean by this, since it isn't something I've seen in other posts – camille Dec 27 '19 at 18:38
  • @camille basically I just want the third bar to become the first one, the first bar to become the second one and the second bar to become the third one. – Euler_Salter Dec 27 '19 at 18:40
  • 1
    Like this? https://stackoverflow.com/q/30633741/5325862 – camille Dec 27 '19 at 18:45
  • @camille I think so.. let me study that for a bit – Euler_Salter Dec 27 '19 at 18:51
  • I think it works yes! Would you also be able to help me on [this](https://stackoverflow.com/questions/59504838/plotly-r-with-ggplot2-use-coord-polar-in-a-geom-bar-using-plotly) question? – Euler_Salter Dec 27 '19 at 19:03
  • @Euler_Salter am I mistaken or the solution proposed by @camille involves editing the dataframe by adding a `count` column against which call `reorder`? – anddt Dec 27 '19 at 20:40

0 Answers0