0

Good evening!

I am trying to plot a categorical variable which is the genre of movies (such as comedy ...) My code looks as following:

  ggplot(df, aes(x=Genre))+
  geom_bar(color="black",fill="blue", alpha=0.5)+ 
  labs(title="Movies per Genre", x="Genre", y="Sum")

enter image description here

I would like to order the marplot in ascending/descending order. I found some solutions using "reorder" in aes and setting a "-" in front of one of the variables. However, the problem I am facing is that I do not have a Y variable for the count. Is there any other solution to this problem?

Thank you very much!

chrtpmdr
  • 35
  • 6
  • `ggplot2` really prefers to use either the order of the `levels` if the x-axis is `factor`, or the lexicographic sort of the labels. Is there a time in the life-cycle of `df` that you actually have the count available and can `factor(Genre, levels=...)`? – r2evans Jan 12 '21 at 17:21
  • The normal method with `reorder()` will work. Use `FUN = sum` inside reorder instead of the default `FUN = mean` if you're actually summing something, or `length` if you just want counts. See, e.g., [Alex Brown's](https://stackoverflow.com/a/9231857/903061) answer at the FAQ for an example with `reorder`. `aes(x = reorder(Genre, Genre, FUN = length))`. – Gregor Thomas Jan 12 '21 at 17:23
  • Will `scale_x_discrete(limits=c('Comedy', 'Romance', 'Drama', 'Animation', 'Action', 'Fantasy'))` work? See https://stackoverflow.com/questions/3253641/order-discrete-x-scale-by-frequency-value – TTS Jan 12 '21 at 17:24
  • 1
    @TTS presumably the goal is to have code that generalizes the ordering, rather than manually entering the correct order for each dataset or data update, which is both slow and error prone. – Gregor Thomas Jan 12 '21 at 17:27
  • I came to the solution by reordering the factor levels the way I wanted them to be displayed in the plot: df$Genre <- as.factor(df$Genre) df$Genre <- factor(df$Genre, levels = c("Fantasy", "Action", "Animation", "Drama", "Romance", "Comedy")) – chrtpmdr Jan 12 '21 at 18:07

0 Answers0