Plotnine(ggplot):指定图例行数时设置图例元素排列方向
Fix for Horizontal Legend Layout in Plotnine
The issue occurs because using nrow=2 in guide_legend forces the legend to arrange items vertically (filling columns first) instead of horizontal left-to-right rows. To fix this, replace nrow with ncol to specify the number of columns, which will make items flow left-to-right across rows as you want.
With 11 date categories, setting ncol=6 splits them into two rows (6 items in the first row, 5 in the second), matching your desired layout.
Here's the corrected code:
import pandas as pd import numpy as np from plotnine import ggplot, aes, theme_light, geom_bar, labs, scale_fill_manual, guides, guide_legend, theme, element_blank 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]) # Replace nrow=2 with ncol=6 to enable horizontal row flow + guides(fill=guide_legend(ncol=6, order=1)) + theme( legend_title=element_blank(), legend_direction='horizontal', legend_position='bottom', legend_box_spacing=0.25, ) ) p
Key Changes:
- Replaced
guide_legend(nrow=2, order=1)withguide_legend(ncol=6, order=1): This tells Plotnine to arrange legend items into 6 columns, filling left-to-right across rows instead of top-to-bottom down columns. - The existing
legend_direction='horizontal'setting works correctly withncolto maintain the desired flow.
内容的提问来源于stack exchange,提问作者brb
相关产品推荐
相关产品推荐

