I am doing this in plotnine, but hoping ggplotters can assist as well.
Consider the following plot:
JavaScript
x
22
22
1
df = pd.DataFrame({
2
'date' : pd.date_range(start='30/09/2019', periods=11, freq='Q').repeat(6),
3
'variable' : ['A','B','C','D','E','F']*11,
4
'value' : np.random.choice(range(50),66)
5
})
6
7
8
p = (ggplot(df, aes(x='variable', y='value', fill='factor(date)'))
9
+ theme_light()
10
+ geom_bar(stat='identity', position='dodge', color='white', size=0.2)
11
+ labs(x=None, y=None)
12
+ 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])
13
+ guides(fill=guide_legend(nrow=2, order=1))
14
+ theme(
15
legend_title=element_blank(),
16
legend_direction='horizontal',
17
legend_position='bottom',
18
legend_box_spacing=0.25,
19
)
20
)
21
p
22
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
Advertisement
Answer
As in ggplot2
this could be achieved via the byrow
argument of guide_legend
. Simply set it to True
:
JavaScript
1
26
26
1
import pandas as pd
2
import numpy as np
3
from plotnine import *
4
5
df = pd.DataFrame({
6
'date' : pd.date_range(start='30/09/2019', periods=11, freq='Q').repeat(6),
7
'variable' : ['A','B','C','D','E','F']*11,
8
'value' : np.random.choice(range(50),66)
9
})
10
11
12
p = (ggplot(df, aes(x='variable', y='value', fill='factor(date)'))
13
+ theme_light()
14
+ geom_bar(stat='identity', position='dodge', color='white', size=0.2)
15
+ labs(x=None, y=None)
16
+ 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])
17
+ guides(fill=guide_legend(nrow=2, order=1, byrow = True))
18
+ theme(
19
legend_title=element_blank(),
20
legend_direction='horizontal',
21
legend_position='bottom'
22
legend_box_spacing=0.25,
23
)
24
)
25
p
26