如何将条形图标签移动到Y轴?

时间:2020-05-10 17:34:05

标签: python matplotlib bar-chart

我希望在Y轴上而不是条形图的顶部标记条形标签。 有办法吗?

enter image description here

我有一段很长的代码可以重新创建该图,因此仅复制其中的一部分。我唯一的想法是通过ax.patches一个接一个地完成它。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000,200000,3650), 
                   np.random.normal(43000,100000,3650), 
                   np.random.normal(43500,140000,3650), 
                   np.random.normal(48000,70000,3650)], 
                  index=[1992,1993,1994,1995])
df
....
bar_plot = plt.bar(df.index, df.mean(axis=1),yerr=upper, edgecolor='indigo', color=color)  
for i in ax.patches:

    ax.text(i.get_x()+0.2, i.get_height()-5.8, \
            str(round((i.get_height()), 1)), fontsize=14, color='darkblue')

1 个答案:

答案 0 :(得分:1)

还要在y轴上显示高度,可以在这些位置引入较小的y刻度。 (可选)可以在此处绘制网格线。

为使次要y刻度标签不干扰主要y刻度标签,可能的方法是增大刻度,使刻度向左移动。

其他可能性是完全删除主要刻度线(plt.yticks([])),或在右侧绘制任一刻度线。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, FormatStrFormatter

np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000, 200000, 3650),
                   np.random.normal(43000, 100000, 3650),
                   np.random.normal(43500, 140000, 3650),
                   np.random.normal(48000, 70000, 3650)],
                  index=[1992, 1993, 1994, 1995])
means = df.mean(axis=1)
bar_plot = plt.bar(df.index, means, edgecolor='indigo',
                   color=[plt.cm.inferno(i / df.shape[0]) for i in range(df.shape[0])])
plt.xticks(df.index)
ax = plt.gca()
ax.yaxis.set_minor_locator(FixedLocator(means))
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.2f"))
ax.tick_params(axis='y', which='minor', length=40, color='r', labelcolor='r', labelleft=True)
plt.grid(axis='y', which='minor', color='r', ls='--')
plt.tight_layout()
plt.show()

example plot