Matplotlib Plot Lines Above Each Bar

对着背影说爱祢 提交于 2019-12-10 17:49:07

问题


I would like to plot a horizontal line above each bar in this chart. The y-axis location of each bar depends on the variable 'target.' I want to use axhline, if possible, or Line2D because I need to be able to modify the line style, color, length, and width.

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()

Thanks in advance!


回答1:


You need to provide the x_start and x_end to .hlines(). They can be numpy.arrays, in which case each element determines the start/end point of each line segment:

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)



来源:https://stackoverflow.com/questions/34007883/matplotlib-plot-lines-above-each-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!