2015-11-30 2 views
3

Я хотел бы построить горизонтальную линию над каждой полосой на этой диаграмме. Расположение оси Y каждого стержня зависит от переменной «цель». Я хочу использовать axhline, если возможно, или Line2D, потому что мне нужно иметь возможность изменять стиль, цвет, длину и ширину линии.Matplotlib Plot Lines Над каждым баром

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

Заранее благодарен!

ответ

2

Необходимо указать x_start и x_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

+0

Благодаря, КТ Zhu. Кстати, можно ли это сделать также с помощью plt.plot? –

+0

Nevermind, я нашел этот ответ здесь: http://stackoverflow.com/questions/16189928/understanding-matplotlib-verts –