DaniB
DaniB

Reputation: 200

Sort Grouped stacked Barplot by factor

I am using R with ggplot and I am struggling with sorting in the desired order a grouped barchart.

The code used so far is the following:

levels(data.m$variable) <- c("% Worried about emigration", "% Worried both immigration and emigration", 
                             "% Worried about immigration", "% Neither / don't know")

require(forcats)

ggplot(data.m, aes(fill = variable, Countries, value))+
  geom_bar(position = 'stack', stat = 'identity')+
  expand_limits(x=c(0,0))+
  coord_flip()

That returns me this chart:

![Text](D:\nuovo\universita\tesi\immagini\worriedCountries.png)

However, I would like to have y-axis of this chart sorted by the countries that are more worried about "Emigration".

Could somebody help me out with this?

Upvotes: 0

Views: 244

Answers (1)

vpz
vpz

Reputation: 1044

One tip: Be careful with levels(data.m$variable)<-..., factors are tricky, it can change the values of this column of yours data. Check it out Give a look if it helps you, the trick is to use scale_x_discrete(limits=...):

library(ggplot2)
library(dplyr)
#Dummy data
data.m = data.frame(Countries = c(rep("A",4),rep("B",4),rep("C",4)),
                    value = c(c(1,2,3,4),c(4,3,2,1),c(2,3,1,4))/10,
                    variable = factor(
                                  rep(c("% Worried about emigration", "% Worried both immigration and emigration", 
                                     "% Worried about immigration", "% Neither / don't know"),
                                   3), levels = c("% Worried about emigration", "% Worried both immigration and emigration", 
                                                  "% Worried about immigration", "% Neither / don't know"))
                    )

yticks = data.m %>% filter(variable=="% Worried about emigration") %>% arrange(value) %>% pull(Countries) %>% as.character()

## If you want it in descendant order use 'arrange(desc(value))'


ggplot(data.m,aes(fill = variable,Countries,value))+
  geom_bar(position = 'stack', stat = 'identity')+
  coord_flip()+
  scale_x_discrete(limits = yticks)

The output: image

Upvotes: 1

Related Questions