0

I have this 3-column data frame that I want to plot a bar chart with ggplot. Although I have ordered the rows in the sequence that I want them to show in the bar chart, ggplot seemed to changed the bar sequence in the way I don't want to.

My sample data frame is:

    sample.df <- data.frame(checking_balance = c("< 0 DM","< 0 DM", "1 - 200 
         DM","1 - 200 DM","> 200 DM","> 200 DM"), default = 
         c("no","yes","no","yes","no","yes"), n = c(139,135,164,105,49,14))

My codes to ggplot the bar chart is:

    sample.qq <- ggplot(sample.df, aes(checking_balance, n)) + geom_bar(stat 
         = "identity", aes(fill = default), position = "dodge") + 
         ggtitle("checking balance vs default status") + theme(plot.title = 
         element_text(hjust = 0.5))+ scale_fill_manual(values=c("#66CC99", 
         "#CC6666"))

   sample.qq

Ideally, on the x axis the labels should be < 0 DM ,1 - 200 DM ,> 200 DM which indicates different income thresholds incrementally, but the ggplot just changed that intended sequence and I need a solution. Thanks a lot!

Edward Lin
  • 609
  • 1
  • 9
  • 16
  • Set the order by converting `checking_balance` to a factor: `sample.df$checking_balance = factor(sample.df$checking_balance, levels=c("< 0 DM" ,"1 - 200 DM" ,"> 200 DM"))`. – eipi10 Nov 27 '17 at 17:38
  • Thank you so much @eipi10. I see the key is to use `levels=` to assign the desired sequence. Nice! – Edward Lin Nov 27 '17 at 17:43

0 Answers0