How to order subgroups in the ggplot bar bar?

I would like to order groups both in the legend and in the ggplot graphic created using geom_bar.

Here is an example

mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), mysubgroup = c("north", "west", "south", "east", "north", "west", "south", "east"), value = c(5,10,6,12, 4, 4, 3, 5)) 

My starting point:

 myplot <- ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) + geom_bar(position = "dodge", width = 0.5, stat = "identity") myplot 

enter image description here

I would like to have both a legend and a bar, drawn in the order of "north", "south", "east", "west".

I tried adding scale_fill_discrete(limits = c("north", "south", "east", "west")) to the plot. It puts the legend in the desired order, but not in the bars (although the lines are rearranged).

 myplot + scale_fill_discrete(limits = c("north", "south", "east", "west")) 

even if I reorder the data, I get the same result as above:

 mydata2 <- mydata[c(1,3,4,2,5,7,8,6),] myplot2 <- ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + geom_bar(position = "dodge", width = 0.5, stat = "identity") myplot2 + scale_fill_discrete(limits = c("north", "south", "east", "west")) 

enter image description here

+4
source share
1 answer

I understood the answer when writing the question (and will post as CW to invite contributions) ...

The answer is for the subgroup to be a β€œfactor” with levels in the right order:

 mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), mysubgroup = factor(c("north", "west", "south", "east", "north", "west", "south", "east"), levels = c("north", "south", "east", "west")), value = c(5,10,6,12, 4, 4, 3, 5)) ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) + geom_bar(position = "dodge", width = 0.5, stat = "identity") 
+4
source

Source: https://habr.com/ru/post/1480548/


All Articles