Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib axvline truth ambiguous or list issue?

I'm trying to plot some vertical lines on a chart that has a "list" of integers (1...300) and some "values" (floats). The following works when x=[48], but when x is set to x=[48, 83, 155, 292], the following code:

pylab.plot(list, values, label='Trend', color='k', linestyle='-')
pylab.axvline(x, linewidth=1, color='g')

Generates this error:

  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2053, in axvline
    ret = ax.axvline(x, ymin, ymax, **kwargs)   File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 3478, in axvline
    scalex = (xx<xmin) or (xx>xmax) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

What does it mean? (I thought it was pretty funny that python pretends to knows when truth is ambiguous). Can I not pass a list to axvline?

like image 719
user6972 Avatar asked Jan 23 '14 06:01

user6972


1 Answers

For completeness, there is also the possibility of using matplotlib.pyplots vlines. This function accepts a list of x-coordinates. Furthermore, you can specify where the lines need to start/end with the arguments ymin and ymax. In the case of this question the code would be:

import matplotlib.transforms as mt

fig, ax = plt.subplots()
ax.plot(list, values, label='Trend', color='k', linestyle='-')

trans = mt.blended_transform_factory(ax.transData, ax.transAxes)
ax.vlines(x, ymin=0, ymax=1, linewidth=1, color='g', transform=trans)

Using the transform argument makes it easier to have the lines from the top to the bottom of your plot. You can read more about it here. You can also skip that argument. In that case you have to specify ymin and ymax in actual y-coordinates.

like image 129
westr Avatar answered Nov 15 '22 21:11

westr