luchonacho
luchonacho

Reputation: 7167

Error when ordering grouped bars in ggplot2

My data is in the long format (as required to do the grouped barplot), so that the values for different categories are in one single column. The data is here.

Now, a standard barplot with ggplot2 orders the bars alphabetically (in my case of country names, from Argentina to Uganda). I want to keep the order of countries as it is in the dataframe. Using the suggestion here (i.e. ussing the limits= option inside the scale_x_discrete function) I get the following graph:

enter image description here

My code is this:

mydata <- read_excel("WDR2016Fig215.xls", col_names = TRUE) 

y <- mydata$value
x <- mydata$country
z <- mydata$Skill

ggplot(data=mydata, aes(x=x, y=y, fill=z)) + 
            geom_bar(stat="identity", position=position_dodge(), colour="black") + 
            scale_x_discrete(limits=x) 

The graph is nicely sorted as I want but the x axis is for some reason expanded. Any idea what is the problem?

Upvotes: 1

Views: 57

Answers (1)

Antonios
Antonios

Reputation: 1939

this?

mydata$country <- factor(mydata$country, levels=unique(mydata$country)[1:30])
ggplot(data=mydata, aes(x=country, y=value, fill=Skill)) + 
  geom_bar(stat="identity", position=position_dodge(), colour="black")

Upvotes: 1

Related Questions