1

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

brb
  • 1,123
  • 17
  • 40

1 Answers1

1

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

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Yeah, thanks stefan. I remember seeing that when I learnt about guides(), but couldn't find it again when I googled and couldn't get it to work. Appreciate it. – brb Oct 20 '22 at 14:28
  • What does order=1, order=2 do? I saw that when I was googling but doesn't seem to make any changes... – brb Oct 20 '22 at 14:29
  • You are welcome. I learn a new ggplot2 argument per week. :D The `order` argument is used to set the order in which legends are displayed when you have multiple legends. – stefan Oct 20 '22 at 14:31