Dance Party2
Dance Party2

Reputation: 7546

bar chart dynamic reference line length

I have a reference line in a bar chart, but I want that line to adjust dynamically based on the index length of the x-axis. I'd like the line to start at the left edge of the left-most bar and end at the right edge of the right-most bar. I've noticed that when the value for ind (index) varies, I cannot accurately make the adjustment by using a percentage of ind or a constant for xmin and xmax arguments.

Here's an example slightly modified from the matplotlib site: http://matplotlib.org/examples/pylab_examples/bar_stacked.html

import numpy as np
import matplotlib.pyplot as plt


N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, color='r', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
             bottom=menMeans, yerr=womenStd)

#How do I adjust the length of this line dynamically?
plt.axhline(linewidth=1, color='b', y=np.average(menMeans))
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind + width/2., ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

Thanks in advance!

Upvotes: 0

Views: 651

Answers (1)

You can use the explicitly defined width parameter of the bar plot to manually draw a line which suits your needs:

p1 = plt.bar(ind, menMeans, width, color='r', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
         bottom=menMeans, yerr=womenStd)

#line with adjusted length
plt.plot([min(ind), max(ind)+width], np.average(menMeans)]*2,linewidth=1,color='b')

We just define a pair of x and y coordinates to generate the line as a plot. The x is given by [min(ind), max(ind)+width], and the y is a duplicate vector with values np.average(menMeans). The proper x values can be inferred from the fact that your example code places the xticks at ind+width/2, and we know that the bars' width is exactly width.

Result:

bar plot with adjusted horizontal line

Upvotes: 2

Related Questions