African Yeti
African Yeti

Reputation: 11

How do I reorder plot by multiple variables?

I am trying to reorder plot first by am and then by mpg. Attached in the result in R using ggplot2.

I trying to attain the same result using siuba and plotnine. Below is my code so far.

(
mtcars 
    >> arrange(_.am, _.mpg)
    >> mutate(model = fct_reorder(_.model, _.am))
    >> ggplot(aes(y="mpg", x="model", fill='factor(am)'))
    + geom_col()
    + labs(fill = "Automatic/Manual Transmission")
    + coord_flip()
)

example

Upvotes: 1

Views: 760

Answers (1)

stefan
stefan

Reputation: 125338

UPDATE

As my original answer is no longer working here is an updated version which uses the now available fct_inorder but most importantly resets the index after re-arrangeing the data and before setting the order via fct_inorder. This step was not necessary at the time I posted my original answer and actually looks like a bug to me.

from plotnine import *
from siuba import _, arrange, mutate
from siuba.dply.forcats import fct_inorder

mtcars1 = (
    mtcars 
        >> arrange(-_.am, _.mpg)
    ).reset_index()

(
mtcars1
    >> mutate(name = fct_inorder(_.name))
    >> ggplot(aes(y="mpg", x="name", fill='factor(am)'))
    + geom_col()
    + labs(fill = "Automatic/Manual Transmission")
    + coord_flip()
)

enter image description here

Original answer

If I should replicate your plot in R I would make use of dplyr::arrange + forcats::fct_inorder. As siuba does not offer an equivalent to fct_inorder you could achieve your desired result by first arranging in your desired order, adding an index column of row numbers and reordering by this index column:

from plotnine import *
from siuba import _, arrange, mutate
from siuba.dply.forcats import fct_reorder
(
mtcars 
    >> arrange(-_.am, _.mpg)
    >> mutate(model = fct_reorder(_.model, _.reset_index().index))
    >> ggplot(aes(y="mpg", x="model", fill='factor(am)'))
    + geom_col()
    + labs(fill = "Automatic/Manual Transmission")
    + coord_flip()
)

enter image description here

Upvotes: 1

Related Questions