Nawahke
Nawahke

Reputation: 5

Customise the order of bar segments in a ggplot with geom_bar fill

I'm trying to make a chart that shows the proportions of the emotions in the songtext of different music styles. I have got this chart, which is already quite satisfacting, but it would be much easier to read if I could choose the order in which thoose emotions are shown, I could group the positive together in a color and the negatives in a other range of color.

Chart: Emotions proportions in songtext by music style I tried to rearrange the emotions before ploting, but ggplot seems to reorder them, I don't know why.

    datasorted <- datasorted %>% arrange(factor(track.lyrics.predominantsentiment,
                                            levels = c("joy","trust","disgust",
                                                       "fear","anger","sadness")))


datasorted %>% filter(track.tag %in% c("Rap","R&B", "Pop", "Rock")) %>% group_by(track.tag) %>%
  ggplot(aes(x=track.tag, fill=track.lyrics.predominantsentiment,
  order=track.lyrics.predominantsentiment)) + 
  geom_bar(position = "fill")

that order condition has no effect on the chart, I tried with it and without.

Does somebody know how to change the order? and how I could choose the colors of the barsections?

Thanks a lot

Upvotes: 0

Views: 82

Answers (1)

Mojoesque
Mojoesque

Reputation: 1318

It will be much easier to help you if you provide a reproducible example of your problem.

You need to not only arrange the data, but change the order of levels of the data:

      datasorted <- datasorted %>% 
        mutate(track.lyrics.predominantsentiment = 
               fct_relevel(track.lyrics.predominantsentiment, 
                           c("joy","trust","disgust", "fear","anger","sadness")))

The colors can now be changed with a scale such as scale_fill_manual.

Upvotes: 1

Related Questions