0

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?

DaniB
  • 200
  • 2
  • 15
  • 1
    The y-axis is plotted in alphabetical order. You'll need to define the "Countries" variable as a factor with the levels (country names) in the desired order. See this similar question/answer: https://stackoverflow.com/questions/36438883/reorder-stacks-in-horizontal-stacked-barplot-r/36439557#36439557 – Dave2e Mar 21 '20 at 14:20

1 Answers1

1

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

vpz
  • 984
  • 1
  • 15
  • 26
  • 1
    Great, it worked! What if I also want to plot in the right order the levels of 'variable'? 1)colour red 2)green and so on? In the same order as they are in the legend – DaniB Mar 21 '20 at 15:24
  • 1
    To keep the order of colors use "variable = factor(variable, levels = {order_of_colors})" when you are building the data.frame, as in my code above. This way you keep the order of factors without change their values. – vpz Mar 21 '20 at 15:30