MATPLOTLIB-多个条的条标题

我是python / matplotlib的新手,我需要一些帮助,将条形标题添加到我的所有条形中。当前,此代码创建一个条形图,每个系列中的标题仅位于一个条形上,我不确定发生了什么,非常感谢您的帮助。数据无关紧要,只是试图准备好代码。

from matplotlib import pyplot as plt
import numpy as np

plt.style.use(['science', 'no-latex'])

system_x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
x_indexes = np.arange(len(system_x))
width = 0.2

cof_diamond = [1, 1, 2, 3, 1, 4, 2]
for i, v in enumerate(cof_diamond):
    plt.text(x_indexes[i] - 0.35, v + 0.05, str(v), color='black')
plt.bar(x_indexes - width, cof_diamond, label='diamond', color='crimson', width=width)

cof_3000 = [1, 1, 2, 3, 1, 4, 2]
for i, v in enumerate(cof_3000):
    plt.text(x_indexes[i] - 0.35, v + 0.05, str(v), color='black')
plt.bar(x_indexes, cof_3000, label='$ta-C_{3000K}$', color='slategrey', width=width)

cof_4000 = [1, 1, 2, 3, 1, 4, 2]
for i, v in enumerate(cof_4000):
    plt.text(x_indexes[i] - 0.35, v + 0.05, str(v), color='black')
plt.bar(x_indexes + width, cof_4000, label='$ta-C_{4000K}$', color='orange', width=width)

plt.xticks(ticks=x_indexes, labels=system_x)

plt.xlabel('System Type')
plt.ylabel('CoF')
plt.title('Mean CoF')

leg = plt.legend()

leg_lines = leg.get_lines()
leg_texts = leg.get_texts()

plt.setp(leg_lines, linewidth=4)

plt.grid(False)

plt.tight_layout()
plt.show()
评论
yyzs1995
yyzs1995

All three of your plt.text calls have the same X coordinates.

更改为

plt.text(x_indexes[i] - 0.35, v + 0.05, str(v), color='black')
...
plt.text(x_indexes[i], v + 0.05, str(v), color='black')
...
plt.text(x_indexes[i] + 0.35, v + 0.05, str(v), color='black')

将修复它。您可以将0.35更改为更合适的数字,以使其看起来更漂亮。

点赞
评论