Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Plotnine (ggplot) : Set the direction legend elements are populated when specifying n rows

I am doing this in plotnine, but hoping ggplotters can assist as well.

Consider the following plot:

df = pd.DataFrame({
    'date' : pd.date_range(start='30/09/2019', periods=11, freq='Q').repeat(6),
    'variable' : ['A','B','C','D','E','F']*11,
    'value' : np.random.choice(range(50),66)
})


p = (ggplot(df, aes(x='variable', y='value', fill='factor(date)'))
  + theme_light()
  + geom_bar(stat='identity', position='dodge', color='white', size=0.2)
  + labs(x=None, y=None)
  + scale_fill_manual(('#80C3D7','#66B7CE','#4DABC6','#339FBE','#1A93B6','#0087AE','#007A9D','#006C8B','#005F7A','#005168','#004457'), labels= lambda l: [v.strftime('%b-%Y') for v in l])  
  + guides(fill=guide_legend(nrow=2, order=1))
  + theme(
        legend_title=element_blank(),
        legend_direction='horizontal',
        legend_position='bottom',
        legend_box_spacing=0.25,
  )
)
p

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like the dates to be arranged from left to right, not top to bottom. For example, I want the first row to be Sep-2019, Dec-2019, Mar-2020, Jun-2020, Sep-2020 etc.

I have tried different version of order=1 without success.

Thanks

>Solution :

As in ggplot2 this could be achieved via the byrow argument of guide_legend. Simply set it to True:

import pandas as pd
import numpy as np
from plotnine import *

df = pd.DataFrame({
    'date' : pd.date_range(start='30/09/2019', periods=11, freq='Q').repeat(6),
    'variable' : ['A','B','C','D','E','F']*11,
    'value' : np.random.choice(range(50),66)
})


p = (ggplot(df, aes(x='variable', y='value', fill='factor(date)'))
  + theme_light()
  + geom_bar(stat='identity', position='dodge', color='white', size=0.2)
  + labs(x=None, y=None)
  + scale_fill_manual(('#80C3D7','#66B7CE','#4DABC6','#339FBE','#1A93B6','#0087AE','#007A9D','#006C8B','#005F7A','#005168','#004457'), labels= lambda l: [v.strftime('%b-%Y') for v in l])  
  + guides(fill=guide_legend(nrow=2, order=1, byrow = True))
  + theme(
        legend_title=element_blank(),
        legend_direction='horizontal',
        legend_position='bottom'
        legend_box_spacing=0.25,
  )
)
p 

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading