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

Time:10-21

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

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

CodePudding user response:

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

  • Related