【问题标题】:How to change space between bars when drawing multiple barplots in pandas?在熊猫中绘制多个条形图时如何更改条形之间的空间?
【发布时间】:2016-04-12 23:44:14
【问题描述】:

我正在使用以下 DataFrame.plot 调用绘制多个条形图:

df.plot(kind='bar',
         stacked=False, 
         figsize=figsize,
         rot=0,
         alpha=0.5, 
         width=width)

但是,我想增加每个类别中条形之间的大小。我怎样才能做到这一点?

【问题讨论】:

  • 嗯,一个丑陋的方法是增加边缘宽度:df.plot(kind='bar', stacked=False, figsize=figsize, rot=0, alpha=0.5, width=width, linewidth = 4) 或类似
  • 对不起,您是指每组内的条之间的“空间”还是条的大小(宽度)?
  • @FabioLamanna 我对此的理解是每个条形之间的宽度,OP 已经通过 width 参数,这将增加每个组之间的间距
  • @kyrre 您在这里使用的颜色图是什么?看起来很棒!

标签: python pandas matplotlib


【解决方案1】:

您可以在条形周围定义边缘并更改其宽度:

df.plot(kind='bar', edgecolor='white', linewidth=3)

如果您想更改组内条形之间的间距,它会起作用。

【讨论】:

    【解决方案2】:

    当他们没有提供这样做的论据时,似乎不值得用 df.plot() 来修复它。如果您不坚持 pandas.plot,您可以使用 Plotly 轻松实现您的目标。通过修改 bargap=0.2,bargroupgap=0.5 可以进行调整,直到达到想要的结果。

    import plotly.graph_objects as go
    
    animals = ['snail', 'pig', 'elephant',
         'rabbit', 'giraffe', 'coyote', 'horse']
    
    fig = go.Figure()
    fig.add_trace(go.Bar(
    x=animals,
    y=[0.1, 17.5, 40, 48, 52, 69, 88],
    name='speed',
    marker_color='red'
    ))
    fig.add_trace(go.Bar(
    x=animals,
    y=[2, 8, 70, 1.5, 25, 12, 28],
    name='lifespan',
    marker_color='blue' 
    ))
    
    # Here we modify the tickangle of the xaxis, resulting in rotated labels.
    fig.update_layout(barmode='group', xaxis_tickangle=-45,bargap=0.2,bargroupgap=0.5)
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2017-12-17
      • 2021-06-16
      • 2023-04-04
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2017-03-09
      相关资源
      最近更新 更多