2

I have this simple code, trying to plot the figure. My intention was to plot the x axis ordered as what I made, i.e. the same as order_num: from 1:10 and then 10+. However, ggplot changed my order. How could I keep the original order I put them in the data frame.

    data_order=data.frame(order_num=as.factor(c(rep(1:10),"10+")),
    ratio=c(0.18223,0.1561,0.14177,0.1163,0.09646,
    0.07518,0.05699,0.04,0.0345,0.02668,0.006725))

    ggplot(data_order,aes(x=order_num,y=ratio))+geom_bar(stat = 'identity')

enter image description here

Prradep
  • 5,506
  • 5
  • 43
  • 84
yangyang
  • 125
  • 1
  • 6
  • 1
    Possible duplicate of [Order Bars in ggplot2 bar graph](https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph) – erc Aug 22 '17 at 08:51

1 Answers1

3

Reading the data: (Notice the removal of as.factor, we will be doing it in the next step. This is not mandatory!)

data_order=data.frame(order_num=c(rep(1:10),"10+"),
                      ratio=c(0.18223,0.1561,0.14177,0.1163,0.09646,
                              0.07518,0.05699,0.04,0.0345,0.02668,0.006725))

You need to work with the dataframe instead of the ggplot.

data_order$order_num <- factor(data_order$order_num, levels = data_order$order_num)

Once you change the levels, it will be as expected.

ggplot(data_order,aes(x=order_num,y=ratio))+geom_bar(stat = 'identity')

enter image description here

Prradep
  • 5,506
  • 5
  • 43
  • 84
  • this indeed changed the order of the x label. But the ratio didn't change accordingly. As you can see from my original figure, when x=2, it should be the second highest. – yangyang Aug 23 '17 at 00:51
  • Based on your comment, I found a solution:x_order_tot=factor(c(rep(1:10),"10+"),levels = factor(c(rep(1:11)))) data_order=data.frame(order_num=x_order_tot, ratio=c(0.18223,0.1561,0.14177,0.1163,0.09646,0.07518,0.05699,0.04,0.0345,0.02668,0.006725)) – yangyang Aug 23 '17 at 01:05
  • Glad that it helped you in arriving at the solution. @yangyang Please check the updated solution now. – Prradep Aug 23 '17 at 07:06