user8268123
user8268123

Reputation:

keep the original order when using ggplot

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

Upvotes: 3

Views: 5752

Answers (1)

Prradep
Prradep

Reputation: 5716

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

Upvotes: 4

Related Questions