如何在条形图matplotlib中添加垂直居中的标签

How to add vertically centered labels in bar chart matplotlib

我有一个问题,我简化如下,如果有人向我推荐 seaborn 中的代码,就像我想要实现的那样,我会很高兴。

import matplotlib.pyplot as plt


a = [2000, 4000, 3000, 8000, 6000, 3000, 3000, 4000, 2000, 4000, 3000, 8000, 6000, 3000, 3000, 4000, 2000, 4000, 3000, 8000, 6000, 3000, 3000, 4000]
b = [0.8, 0.9, 0.83, 0.81, 0.86, 0.89, 0.89, 0.8, 0.8, 0.9, 0.83, 0.81, 0.86, 0.89, 0.89, 0.8, 0.8, 0.9, 0.83, 0.81, 0.86, 0.89, 0.89, 0.8]
c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

fig1, ax1 = plt.subplots(figsize=(12, 6))
ax12 = ax1.twinx()

ax1.bar(c, a)
ax12.plot(c, b, 'o-', color="red", markersize=12,
          markerfacecolor='Yellow', markeredgewidth=2, linewidth=2)
ax12.set_ylim(bottom=0, top=1, emit=True, auto=False)

plt.grid()
plt.show()

我正在尝试实现如下图所示的居中和垂直的标签。

自 matplotlib 3.4.0 起,使用 Axes.bar_label:

  • label_type='center' 将标签放在条形的中心
  • rotation=90 将它们旋转 90 度

由于这是一张普通的条形图,我们只需要标记一个条形容器ax1.containers[0]:

ax1.bar_label(ax1.containers[0], label_type='center', rotation=90, color='white')

但如果这是一个 grouped/stacked 条形图,我们应该迭代所有 ax1.containers:

for container in ax1.containers:
    ax1.bar_label(container, label_type='center', rotation=90, color='white')


seaborn 版本

我刚刚注意到问题文本询问关于 seaborn 的问题,在这种情况下我们可以通过底层轴使用 sns.barplot and sns.pointplot. We can still

import pandas as pd
import seaborn as sns

# put the lists into a DataFrame
df = pd.DataFrame({'a': a, 'b': b, 'c': c})

# create the barplot and vertically centered labels
ax1 = sns.barplot(data=df, x='c', y='a', color='green')
ax1.bar_label(ax1.containers[0], label_type='center', rotation=90, color='white')

ax12 = ax1.twinx()
ax12.set_ylim(bottom=0, top=1, emit=True, auto=False)

# create the pointplot with x=[0, 1, 2, ...]
# this is because that's where the bars are located (due to being categorical)
sns.pointplot(ax=ax12, data=df.reset_index(), x='index', y='b', color='red')