Python 在MatPlotlib图形中的每个条形顶部添加一条线

Python 在MatPlotlib图形中的每个条形顶部添加一条线,python,matplotlib,graph,Python,Matplotlib,Graph,我有下面图表的代码。我需要为每个图添加一个阈值。此值在不同的组之间确实会发生变化 import numpy as np import matplotlib.pyplot as plt n_groups = 4 heuristic = (230.193, 33.96, 46, 8) safe = (195.8, 24.83, 36, 7) # create plot fig, ax = plt.subplots() index = np.arange(n_groups) bar_width =

我有下面图表的代码。我需要为每个图添加一个阈值。此值在不同的组之间确实会发生变化

import numpy as np
import matplotlib.pyplot as plt

n_groups = 4
heuristic = (230.193, 33.96, 46, 8)
safe = (195.8, 24.83, 36, 7)

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.1
opacity = 0.8

rects1 = plt.bar(index, heuristic, bar_width,
             marker="D",
             alpha=opacity,
             color='b',
             label='Heuristic')

rects2 = plt.bar(index + bar_width, safe, bar_width,
             alpha=opacity,
             color='g',
             label='SAFE')

plt.xlabel('Firmware')
plt.ylabel('nDCG')
plt.title('Matching results by firmware')
plt.xticks(index + bar_width, ('Mqtt', 'Solder', 'Iron', 'Sympetrum'))
plt.legend()

plt.tight_layout()
plt.show()
下面是它生成的图形,我使用了粉色标记来显示我希望代码生成的内容。对不起,电话线不直。非常感谢您的帮助。谢谢

以下是一种使用方法:

输出:

import numpy as np
import matplotlib.pyplot as plt

n_groups = 4
heuristic = (230.193, 33.96, 46, 8)
safe = (195.8, 24.83, 36, 7)
threshold = (250, 50, 80, 30)

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.1
opacity = 0.8

rects1 = plt.bar(index, heuristic, bar_width,
             #marker="D",
             alpha=opacity,
             color='b',
             label='Heuristic')

rects2 = plt.bar(index + bar_width, safe, bar_width,
             alpha=opacity,
             color='g',
             label='SAFE')

[
    ax.hlines(
        threshold[i],
        index[i] - bar_width / 2,
        index[i] + bar_width * 1.5,
        colors="deeppink",
    )
    for i in range(len(safe))
]

plt.xlabel('Firmware')
plt.ylabel('nDCG')
plt.title('Matching results by firmware')
plt.xticks(index + bar_width, ('Mqtt', 'Solder', 'Iron', 'Sympetrum'))
plt.legend()

plt.tight_layout()
plt.show()