Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the order of stacked fill columns in ggplot2

Tags:

r

ggplot2

I want to change the order of a stacked bar chart. For example, in mpg I want to order the to c("4", "r", "f")

Is the only approach to change the level of the factors?

library(ggplot2)
library(dplyr)
s <- ggplot(mpg, aes(fl, fill=drv)) + geom_bar(position="stack")
s

enter image description here

like image 380
vinchinzu Avatar asked Oct 30 '17 23:10

vinchinzu


People also ask

How do I change the order of stacked columns?

Under Chart Tools, on the Design tab, in the Data group, click Select Data. In the Select Data Source dialog box, in the Legend Entries (Series) box, click the data series that you want to change the order of. Click the Move Up or Move Down arrows to move the data series to the position that you want.

How can I reorder the stacks in a stacked bar plot?

How can I reorder the stacks in a stacked bar plot? Change the order of the levels of the factor variable you're creating the stacks with in the aes thetic mapping .

How do I change the order of bars in ggplot2?

Reordering in ggplot is done using theme() function. Within this, we use axis. text. x with the appropriate value to re-order accordingly.


1 Answers

The structure of the input data is character:

str(mpg$drv)

> chr [1:234] "f" "f" "f" "f" "f" "f" "f" "4" "4" "4" "4" "4" "4" "4" "4" "4" "4" "4" "r" "r" "r" "r" "r" "r" "r" "r" "r" "r" "4" "4" "4" "4" "f" "f" "f" "f" "f" "f" "f" "f" "f" "f" "f" ...

ggplot will automatically convert character strings to a factor. You can see the default ordering as follows, and this conversion ranks them alphabetically:

levels(as.factor(mpg$drv))
> "4" "f" "r"

To reorder the barplot without changing the original data, you can just refactor the variable within plot itself:

ggplot(mpg, aes(fl, fill = factor(drv, levels=c("4", "r", "f")))) + 
  geom_bar(position="stack") +
  labs(fill = "Drive")

Comparing the results:

enter image description here

like image 125
Michael Harper Avatar answered Nov 14 '22 21:11

Michael Harper