Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep the original order when using ggplot [duplicate]

Tags:

r

ggplot2

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


1 Answers

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

like image 179
Prradep Avatar answered Mar 06 '26 01:03

Prradep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!