Python Forum
Error with MatPlotLib subplots
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error with MatPlotLib subplots
#1
Question 
Hi.

I've been trying to create subplots with MatPlotLib, FinPlot, Ta-Lib, and Seaborn. Constant errors. I've tried Python V 3.9.x and 3.10.x using both PyCharm and Visual Studio Code using my own code and multiple samples of code copied from the internet. Here is one sample:

    # ----------- Test ------------
    
    plt.rcParams["figure.figsize"] = [7.50, 3.50]
    plt.rcParams["figure.autolayout"] = True

    fig, (ax1, ax2) = plt.subplots(2)
    df = pd.DataFrame(dict(name=["Joe", "James", "Jack"], age=[23, 34, 26]))

    df.set_index("name").plot(ax=ax1)
    df.set_index("name").plot(ax=ax2)

    plt.show()

    # ----------- End Test ------------
Note that Matplotlib and pandas are declared at the top of the script:
import matplotlib.pyplot as plt
import pandas as pd 
When executed, it throws this error on the "df = pd.DataFrame(..." command:
Error:
local variable 'pd' referenced before assignment
The code comes from: Tutorials Point - Article "Stuffing a Pandas DataFrame.plot into a Matplotlib subplot". This seems like a reputable site and presumably, the code should work.

In another test function that I created using a datafreme loaded with a custom CSV file, this code:
   
    # ...
    fig, (ax1, ax2) = plt.subplots(2)

    df_cur_daily("Close").plot(ax=ax1)
    df_cur_daily("High").plot(ax=ax2)
    plt.show()
Throws this error when it hits
df_cur_daily("Close").plot(ax=ax1)
Error:
'DataFrame' object is not callable
I've been banging my head on this for hours on many tests like this. I'd appreciate any help. Is there any reason this python code will not work correctly in VS Code? Another approach to plotting a chart? Another library?

Thanks for any advice,

Dan.

p.s. Platform Specs:
  • Apple Macbook Pro M1 Max (latest)
  • 32 GB
  • Python 3.9.10
  • MacOS Monterey V12.3
  • Visual Studio Code V1.65.2 (Universal)
Reply
#2
works for me:
import pandas as pd
import matplotlib.pyplot as plt
# ----------- Test ------------
     
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
 
fig, (ax1, ax2) = plt.subplots(2)
df = pd.DataFrame(dict(name=["Joe", "James", "Jack"], age=[23, 34, 26]))
 
df.set_index("name").plot(ax=ax1)
df.set_index("name").plot(ax=ax2)
 
plt.show()
# ----------- End Test ------------
when posting error traceback, always show complete unaltered error message.
   
Reply
#3
I don't think you have pandas installed. I got the same message when I ran your code. I typed "pip list" and sure enough I didn't have pandas installed in the virtual environment I was using. Maybe you have a similar problem, not installing pandas in the Python you are using.

This is an article about installing Python on a Mac.

https://docs.python.org/3/using/mac.html
Reply
#4
Many thanks for the feedback. I’ll post more info tomorrow, but for now…

After thinking through your feedback, I created a new folder and added one file with the code above. The code worked… sort of. To continue my work, I’m deinstalling Python, VS Code, and PyCharm, and then reinstalling everything from scratch. I’ll report the results tomorrow.

Again, thanks for the help.

Best,

Dan.
Reply
#5
Some interim feedback…

After executing that code, it worked fine until it hit:
 plt.show()
When it hit that command while debugging, VS Code crashed (no error, just “splat”). At that point, I decided that my entire Python dev environment was probably still corrupt somehow. After 30+ years as a professional Windows developer (only two years with Python), I've learned that sometimes it's better and faster to clean things out than trying to debug a corrupt environment.

Some additional factors:
  • I have a mix of Anaconda and Pip
  • Macs with M1 chips are known to have some issues
If I still had my PC workstation, I'd try to fix these issues. With only three months of experience with my new MacBook Pro M1, cleaning out is better. I've learned from my mistakes.

After rebuilding, I'll post more results. Again, thanks for your help.

Best,

Dan.

p.s. Pandas was installed in the 3.9 environment. Going forward, I'm installing V3.10 until it becomes necessary to revert to 3.9.
Reply
#6
try:

# from command line
conda config --set pip_interop_enabled True
pip install <packagename>
conda update --all
Reply
#7
I don't understand what the conda code does. As I mentioned above, I deleted Anaconda. And then deleted and reinstalled Python, PyCharm, and VS Code. After that, I cleaned out $PATH and reset it to the default "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin".

Rerunning the test code above generated the error below when it hit:
# df.set_index("name").plot(ax=ax1)
I changed to code to split the set_index and plot to two different statements:
df.set_index("name")
df.plot(ax=ax1)
It errored on the df.plot(ax=ax1) statement.

When you tested the code, did you use a Mac M1 system? If not, I'm wondering if the issue is specifically related to subplots on M1 Macs.

Regards,

Dan.

p.s. As a test, this simple code plotted successfully.

This worked:
data = [23, 45, 56, 78, 213]
plt.plot([1,2,3,4,5], data)
plt.show()
----------------------

Error:

Traceback (most recent call last):
File "/Users/danieltclark/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.7172.26/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1483, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/danieltclark/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.7172.26/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/danieltclark/Documents/GitHub/OBVTrader2/main.py", line 22, in <module>
df.set_index("name").plot(ax=ax1)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/plotting/_core.py", line 972, in __call__
return plot_backend.plot(data, kind=kind, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py", line 71, in plot
plot_obj.generate()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 335, in generate
self._post_plot_logic_common(ax, self.data)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 526, in _post_plot_logic_common
self._apply_axis_properties(ax.xaxis, rot=self.rot, fontsize=self.fontsize)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 614, in _apply_axis_properties
labels = axis.get_majorticklabels() + axis.get_minorticklabels()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axis.py", line 1201, in get_majorticklabels
ticks = self.get_major_ticks()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axis.py", line 1371, in get_major_ticks
numticks = len(self.get_majorticklocs())
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axis.py", line 1277, in get_majorticklocs
return self.major.locator()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/ticker.py", line 2113, in __call__
vmin, vmax = self.axis.get_view_interval()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axis.py", line 1987, in getter
return getattr(getattr(self.axes, lim_name), attr_name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 781, in viewLim
self._unstale_viewLim()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 776, in _unstale_viewLim
self.autoscale_view(**{f"scale{name}": scale
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 2932, in autoscale_view
handle_single_axis(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 2895, in handle_single_axis
x0, x1 = locator.nonsingular(x0, x1)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/ticker.py", line 1654, in nonsingular
return mtransforms.nonsingular(v0, v1, expander=.05)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/transforms.py", line 2880, in nonsingular
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/getlimits.py", line 462, in __new__
dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable
python-BaseException
Reply
#8
conda is only for anaconda. It serves the same function as pip, but is customized for anaconda.
i didn't read carefully enough, and only saw the word anaconda in your
Quote:As I mentioned above, I deleted Anaconda
so wrong post, ignore it.
Reply
#9
Thumbs Up 
Fixed! Given your great feedback, I thought you deserved a final report...

After much additional effort, I decided that my MacBook installation was corrupt in some way. So I flattened my MacBook - deleted all the contents of the system disk and then:
  1. Reinstalled the MacOS,
  2. Installed only the apps required to test the Python test code.
At that point, the test code ran perfectly.

I wish I could find the underlying issue. But what I've learned over the lst 30+ years of coding is that sometimes it's just better to write off an issue as "smelly stuff happens" and move ahead.

Again, many thanks for your help.

Best,

Dan.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to loop through code to plot seaborn line plots across multiple subplots eyavuz21 0 1,693 Dec-05-2022, 10:46 AM
Last Post: eyavuz21
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,726 Aug-19-2022, 11:07 AM
Last Post: dm222
  Matplotlib: How do I convert Dates from Excel to use in Matplotlib JaneTan 1 3,257 Mar-11-2021, 10:52 AM
Last Post: buran
  Error message when trying to install Matplotlib in Python3.8 Transitionyte 5 5,212 Jan-22-2020, 11:52 PM
Last Post: Transitionyte
  matplotlib pip install error Paul_Grosvenor 3 4,248 Nov-18-2019, 01:11 PM
Last Post: buran
  how to create subplots in for loop? python_newbie09 1 5,916 Sep-25-2019, 02:29 PM
Last Post: stullis
  matplotlib recursion error when repeatedly displaying a surface AdeIsHere 0 1,936 Sep-19-2019, 04:36 PM
Last Post: AdeIsHere
  Subplots on one figure SarahColombo96 0 1,750 Feb-09-2019, 01:09 PM
Last Post: SarahColombo96
  Change distance and title postion in subplots Mark3232 2 2,842 Jul-19-2018, 10:10 AM
Last Post: Mark3232
  Help with plot legends in subplots Felipe 2 5,867 Feb-06-2017, 02:55 PM
Last Post: Felipe

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020