1

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?

luchonacho
  • 6,759
  • 4
  • 35
  • 52
  • Try converting `x` to integers, `x = as.integer(x)`. And `geom_col` is a handy shortcut for `stat = "identity"`. – joran Feb 05 '18 at 23:43

1 Answers1

1

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")
Antonios
  • 1,919
  • 1
  • 11
  • 18
  • That! What is the explanation? – luchonacho Feb 06 '18 at 00:09
  • I reordered mydata$country factor levels to the desired sequence. For reordering factor levels check here https://www.r-bloggers.com/reorder-factor-levels/ and here http://www.cookbook-r.com/Manipulating_data/Changing_the_order_of_levels_of_a_factor/ – Antonios Feb 06 '18 at 07:57