ViSa
ViSa

Reputation: 2247

How to reorder or sort categories based on another variable values in python plotnine?

I am trying to use plotnine in python and couldn't do fct_reorder of r in python. Basically I would like to plot categories from the categorical variable to arrange on x axis based on the increasing value from another variable but I am unable to do so.

import numpy as np
import pandas as pd
from plotnine import *
test_df = pd.DataFrame({'catg': ['a','b','c','d','e'],
                       'val': [3,1,7,2,5]})

test_df['catg'] = test_df['catg'].astype('category')

When I sort & plot this based on .sort_values() then it doesn't rearrange the categories on x axis:

test_df = test_df.sort_values(by = ['val']).reset_index(drop=True)

(ggplot(data = test_df, 
           mapping = aes(x = test_df.iloc[:, 0], y = test_df['val']))
+ geom_line(linetype = 2) 
+ geom_point() 
+ labs(title = str('Weight of Evidence by ' + test_df.columns[0]),
            x = test_df.columns[0],
            y = 'Weight of Evidence') 
+ theme(axis_text_x= element_text(angle = 0))
)

enter image description here

Desired output:

enter image description here

I saw this SO Post where they are using reorder but I couldn't find any reorder in plotnine to work.

Upvotes: 2

Views: 876

Answers (1)

has2k1
has2k1

Reputation: 2375

Plotnine does have reorder. It is an internal function available when creating and aesthetic mapping, just like factor.

In your example you could use it like this:

ggplot(data=test_df, mapping=aes(x='reorder(catg, val)', y='val'))

Upvotes: 1

Related Questions