python - Matplotlib 在每个条形图上方绘制线条

标签 python matplotlib lines

我想在此图表中的每个条形图上方绘制一条水平线。 每个条形的 y 轴位置取决于变量“目标”。 我想使用 axhline(如果可能)或 Line2D,因为我需要能够修改线型、颜色、长度和宽度。

import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline


# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')

#Here are the targets that I want to use 
#to plot horizontal lines above each bar...
targets = (6,6,8,6,9)

ind = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

plt.bar(ind, performance, align='center')
plt.xticks(ind, people)

plt.show()

提前致谢!

最佳答案

您需要将x_startx_end 提供给.hlines()。它们可以是 numpy.array,在这种情况下,每个元素确定每个线段的起点/终点:

import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline


# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')

#Here are the targets that I want to use 
#to plot horizontal lines above each bar...
targets = (6,6,8,6,9)

ind = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

Bars = plt.bar(ind, performance, align='center')
_ = plt.xticks(ind, people)

#if you want your hlines to align with the bars.
#i.e. start and end at the same x coordinates:

x_start = np.array([plt.getp(item, 'x') for item in Bars])
x_end   = x_start+[plt.getp(item, 'width') for item in Bars]

plt.hlines(targets, x_start, x_end)

enter image description here

关于python - Matplotlib 在每个条形图上方绘制线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007883/

相关文章:

python - 如果我只想使用标准用户模型,如何使用 AUTH_USER_MODEL

python - 如果远程服务器上的 python 脚本停止,如何重新启动它?

python - "Replot"IPython 笔记本中的 matplotlib 内联图

c - 逐行、逐字地阅读文本。 C编程

Ruby 相当于 "grep -C 5"以获取匹配项周围的行的上下文?

c++ - 同时支持 Tcl 和 Python?

python - 损失函数增加而不是减少

python - 删除 sudo 来运行 python 脚本

python - 我如何告诉 matplotlib 我完成了一个情节?

C# 如何在使用 Stream Reader 读取文本文件时跳过行数?