【问题标题】:add space between bars in each subgroup in pandas barplot在 pandas barplot 的每个子组中的条之间添加空格
【发布时间】:2020-07-13 16:34:28
【问题描述】:

我有一个这样的数据框:

    chart = pd.DataFrame({'test1_bottom': {'Information Technology': 0.2533668392286677,
  'Health Care': 0.15018887027604233,
  'Financials': 0.11250374171121448,
  'Communication Services': 0.10598698851685082,
  'Consumer Discretionary': 0.09930980115655588,
  'Industrials': 0.08341663798744221,
  'Consumer Staples': 0.077755633372036,
  'Utilities': 0.03633802369644037,
  'Real Estate': 0.030599694393051324,
  'Energy': 0.026211182457138587},
 'test1_top': {'Information Technology': 0.2533668392286677,
  'Health Care': 0.15018887027604233,
  'Financials': 0.11250374171121448,
  'Communication Services': 0.10598698851685082,
  'Consumer Discretionary': 0.09930980115655588,
  'Industrials': 0.08341663798744221,
  'Consumer Staples': 0.077755633372036,
  'Utilities': 0.03633802369644037,
  'Real Estate': 0.030599694393051324,
  'Energy': 0.026211182457138587}})

我试图在每个子组中的条之间添加空格,因为我在每个条上的值标签是重叠的:

figsize=(9,4)
ax = chart.iloc[::-1].plot.barh(figsize=figsize, color=['#0574A0','#FF5233'],width=0.5);
for p in ax.patches:
    v = ax.annotate("{:,.2%}".format(p.get_width()), (p.get_width(), p.get_y() + p.get_height()/4), xytext=(4, -1), 
                textcoords='offset points',ha='left');
plt.legend(loc='lower right',fontsize=10)
plt.tight_layout(pad=-5)

我试图在上面的红色和绿色条之间添加一个小空间。谢谢 可以看到生成的图:

【问题讨论】:

    标签: pandas matplotlib bar-chart


    【解决方案1】:

    您可以进行一些手动绘图和对齐:

    # set up figure
    fig, ax = plt.subplots(figsize=(10,6))
    y=np.arange(len(chart))
    
    # height of bar and gap
    height = 0.4
    gap = 0.02
    
    # plot with plt.barh
    for offset, col in zip([-1,1], chart.columns):
        plt.barh(y + offset * (height+gap)/2, chart[col], height=height, label=col)
    
    for p in ax.patches:
        v = ax.annotate("{:,.2%}".format(p.get_width()), (p.get_width(), p.get_y() + p.get_height()/4), xytext=(4, -1), 
                    textcoords='offset points',ha='left');
    plt.legend(loc='lower right',fontsize=10)
    plt.tight_layout(pad=-5)
    
    # invert the yaxis so you don't need [::-1]
    ax.invert_yaxis()
    
    # force yticks
    plt.yticks(y, chart.index)
    plt.show()
    

    输出:

    【讨论】:

    • 那么如果有任意数量的列我该怎么办?即如果有3列怎么办?我在哪里更改您的代码?
    猜你喜欢
    • 2020-04-17
    • 2021-10-20
    • 2010-11-19
    • 2023-02-16
    • 1970-01-01
    • 2011-10-29
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多