pandas - 在 pandas barplot 中的每个子组中的条形之间添加空格

标签 pandas matplotlib bar-chart

我有一个像这样的数据框:

    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)

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

最佳答案

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

# 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()

输出:

enter image description here

关于pandas - 在 pandas barplot 中的每个子组中的条形之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60979149/

相关文章:

python - 对每个级别的 Pandas 中的多索引进行不同的排序

python - 从 3 个不同的 pandas 数据框中查找相同的行,其中行的排序不相似

python - 有没有更好的方法来收集 pandas 中的唯一索引值?

python - 对列进行排名并选择列名称

python - 使用 Pandas 和 Scatter_Matrix 将不会显示

r - 如何在R中的分组条形图中生成堆叠条形图

r - ggplot 错误 : Don't know how to automatically pick scale for object of type function

python-3.x - 我如何在 ReadTheDocs 中将 matplotlib 的 plot-directive 与 python-3 一起使用?

matplotlib - 来自脚本的 Julia pyplot(非交互式)

Python Bokeh - 混合