You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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) with guide_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 with ncol to maintain the desired flow.

内容的提问来源于stack exchange,提问作者brb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:55:35