Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib plotting undefined plot out of nowhere

First of all, I apologize if this is not the place to post these kind of questions.

The issue is that matplotlib is apparently plotting a graph (I can recognize it from an old plot, so it's not some completely random graph) whenever I execute a script. Let me explain further.

The file is a test file, module_test.py and I have been trying to recognize where this problem may come from. Now I have written

import matplotlib.pyplot as plt
plt.show()

literally at the top of the script and when I run the test via python -m package.tests.module_test, that "random" graph pops up. It also pops up with any other test script, but doesn't show up when using python in the command console. The tests run fine otherwise.

Does anybody have any idea why this happens? I have tried deleting __pycache__ from all folders related to the issue, but of no help.

Here is the picture. It's a plot from a lab report I did months ago.

This is the graph

like image 322
mariogarcc Avatar asked Apr 11 '26 09:04

mariogarcc


1 Answers

By way of its emulation of the MATLAB GUI, matplotlib (especially but not only pyplot) is stateful. This is a polite way of saying that it has global variables and all the debugging pain that goes with them.

In particular, every plot created is retained indefinitely so that it can be referenced by its “figure number”. It can also be the “current figure” for pyplot.

Importing a module from a package implicitly imports the containing package(s) first. This is one of the reasons that merely importing a module should not have any side effects (but merely define classes, functions, and constants). The combination of invisible side effects and action at a distance produces hilarity like that observed here.

like image 185
Davis Herring Avatar answered Apr 12 '26 22:04

Davis Herring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!