[Tutor] Why does matplotlib error message say that 1 is not a scalar?
David
bouncingcats at gmail.com
Thu Sep 19 03:28:41 EDT 2019
Hi
I am just making some initial attempts to use matplotlib.
I don't understand the below error message.
h means height, b means bottom, these words are used
in the documentation.
$ python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> x = [1, 2, 3]
>>> h = [1, 1, 1]
>>> b = [1, 2, 3]
>>> plt.bar(x, h, bottom=b)
<Container object of 3 artists>
>>> plt.show()
### here the plot displays, and then I close its window ###
>>> plt.bar(x, 1, bottom=b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 2705, in bar
**kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/__init__.py", line
1894, in inner
return func(ax, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line
2079, in bar
"must be length %d or scalar" % nbars)
ValueError: incompatible sizes: argument 'height' must be length 3 or scalar
>>>
What happens above is that first I pass h = [1,1,1]
to plt.bar() to individually specify the height of each box
in the plot.
This works and the call to plt.show() above successfully
draws the plot I expect.
According to the matplotlib documentation, and the error
message, the height (2nd) argument of plt.bar() can be a
scalar. The use case is when you want all boxes to have
the same height.
The docs
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html#matplotlib.pyplot.bar
says
"""
Each of x, height, width, and bottom may either be a scalar applying
to all bars, or it may be a sequence of length N providing a separate
value for each bar.
"""
So I try to pass 1 as the height of all bars, and I expect
to get an identical plot. Instead I get the above error.
Any clues what is going wrong please?
More information about the Tutor
mailing list