The Python Oracle

Barplot with log y-axis program syntax with matplotlib pyplot

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping

--

Chapters
00:00 Barplot With Log Y-Axis Program Syntax With Matplotlib Pyplot
00:53 Answer 1 Score 7
01:22 Accepted Answer Score 1
01:57 Answer 3 Score 4
02:27 Thank you

--

Full question
https://stackoverflow.com/questions/1802...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #typeerror #barchart

#avk47



ANSWER 1

Score 7


Are you sure that is all your code does? Where does the code throw the error? During plotting? Because this works for me:

In [16]: import numpy as np
In [17]: x = np.arange(1,8, 1)
In [18]: y = np.exp(x)

In [20]: import matplotlib.pyplot as plt
In [21]: fig = plt.figure()
In [22]: ax = fig.add_subplot(111)
In [24]: ax.bar(x, y, log=1)
Out[24]: 
[<matplotlib.patches.Rectangle object at 0x3cb1550>,
 <matplotlib.patches.Rectangle object at 0x40598d0>,
 <matplotlib.patches.Rectangle object at 0x4059d10>,
 <matplotlib.patches.Rectangle object at 0x40681d0>,
 <matplotlib.patches.Rectangle object at 0x4068650>,
 <matplotlib.patches.Rectangle object at 0x4068ad0>,
 <matplotlib.patches.Rectangle object at 0x4068f50>]
In [25]: plt.show()

Here's the plot enter image description here




ANSWER 2

Score 4


As already suggested in the comments to Greg's answer, you're indeed seeing an issue that was fixed in matplotlib 1.3 by setting the default behavior to 'clip'. Upgrading to 1.3 fixes the issue for me.

Note that it doesn't seem to matter how you apply the log scale, whether as a keyword argument to bar or via set_yscale on the axis.

See also this answer to "Logarithmic y-axis bins in python" that suggests this workaround:

plt.yscale('log', nonposy='clip')



ACCEPTED ANSWER

Score 1


The error is raised due to the log = True statement in ax.bar(.... I'm unsure if this a matplotlib bug or it is being used in an unintended way. It can easily be fixed by removing the offending argument log=True.

This can be simply remedied by simply logging the y values yourself.

x_values = np.arange(1,8, 1)
y_values = np.exp(x_values)

log_y_values = np.log(y_values)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x_values,log_y_values) #Insert log=True argument to reproduce error

Appropriate labels log(y) need to be adding to be clear it is the log values.