Disable the output of matplotlib pyplot - python

I have an array A of shape (1000, 2000). I use matplotlib.pyplot to plot the array, which means 1000 curves, using
import matplotlib.pyplot as plt
plt(A)
The figure is fine but there are a thousand lines of:
<matplotlib.lines.Line2D at 0xXXXXXXXX>
Can I disable this output?

This output is what the plt function is returning (I presume here you meant to write plt.plot(A)). To suppress this output assign the return object a name:
_ = plt.plot(A)
_ is often used to indicate a temporary object which is not going to be used later on. Note that this output you are seeing will only appear in the interpreter, and not when you run the script from outside the interpreter.

You can also suppress the output by use of ; at the end (assuming you are doing this in some sort of interactive environment)
plot(A);

plt.show()
This way there is no need to create unnecessary variables.
E.g.:
import matplotlib.pyplot as plt
plt.plot(A)
plt.show()

use a semi-colon after the plot command
eg:
plt.imshow(image,cmap);
will display the graph and stop the verbose

To ignore warnings
import warnings
warnings.filterwarnings("ignore")
This will resolve your issue.

Related

Jupyter shows plot with and without plt.show() but with an addition of extra line [duplicate]

I have an array A of shape (1000, 2000). I use matplotlib.pyplot to plot the array, which means 1000 curves, using
import matplotlib.pyplot as plt
plt(A)
The figure is fine but there are a thousand lines of:
<matplotlib.lines.Line2D at 0xXXXXXXXX>
Can I disable this output?
This output is what the plt function is returning (I presume here you meant to write plt.plot(A)). To suppress this output assign the return object a name:
_ = plt.plot(A)
_ is often used to indicate a temporary object which is not going to be used later on. Note that this output you are seeing will only appear in the interpreter, and not when you run the script from outside the interpreter.
You can also suppress the output by use of ; at the end (assuming you are doing this in some sort of interactive environment)
plot(A);
plt.show()
This way there is no need to create unnecessary variables.
E.g.:
import matplotlib.pyplot as plt
plt.plot(A)
plt.show()
use a semi-colon after the plot command
eg:
plt.imshow(image,cmap);
will display the graph and stop the verbose
To ignore warnings
import warnings
warnings.filterwarnings("ignore")
This will resolve your issue.

Function does not finish executing in `hist` function only on second time

In Python DataFrame, Im trying to generate histogram, it gets generated the first time when the function is called. However, when the create_histogram function is called second time it gets stuck at h = df.hist(bins=3, column="amount"). When I say "stuck", I mean to say that it does not finish executing the statement and the execution does not continue to the next line but at the same time it does not give any error or break out from the execution. What is exactly the problem here and how can I fix this?
import matplotlib.pyplot as plt
...
...
def create_histogram(self, field):
df = self.main_df # This is DataFrame
h = df.hist(bins=20, column="amount")
fileContent = StringIO()
plt.savefig(fileContent, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format="png",
transparent=False, bbox_inches=None, pad_inches=0.5,
frameon=None)
content = fileContent.getvalue()
return content
Finally I figured this out myself.
Whenever I executed the function I was always getting the following log message but I was ignoring it due to my lack of awareness.
Backend TkAgg is interactive backend. Turning interactive mode on.
But then I realised that may be its running in interactive mode (which was not my purpose). So, I found out that there is a way to turn it off, which is given below.
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
And this fixed my issue.
NOTE: the use should be called immediately after importing matplotlib in the sequence given here.

Suppressing Pandas dataframe plot output

I am plotting a dataframe:
ax = df.plot()
fig = ax.get_figure()
fig.savefig("{}/{}ts.png".format(IMGPATH, series[pfxlen:]))
It works fine. But, on the console, I get:
/usr/lib64/python2.7/site-packages/matplotlib/axes.py:2542: UserWarning: Attempting to set identical left==right results in singular transformations; automatically expanding. left=736249.924955, right=736249.924955 + 'left=%s, right=%s') % (left, right))
Basic searching hasn't showed me how to solve this error. So, I want to suppress these errors, since they garbage up the console. How can I do this?
Those aren't errors, but warnings. If you aren't concerned by those and just want to silence them, it's as simple as:
import warnings
warnings.filterwarnings('ignore')
Additionally, pandas and other libraries may trigger NumPY floating-point errors. If you encounter those, you have to silence them as well:
import numpy as np
np.seterr('ignore')

IPython InteractiveShell fails to yield rich output when using `%matplotlib inline`

I am writing a custom client (a web-based graph representation of an IPython Notebook) for an IPython application and the easiest way to manage IPython programmatically seems to be using the IPython.core.InteractiveShell instance.
Consider this example: when a Jupyter Notebook cell that uses rich output is executed with inline magic, Notebook shows the appropriate rich representation (a plotted image) of plt.show() inline:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
plt.show()
I want to be able to retrieve the image when using IPython programmatically via its API, namely InteractiveShell, like this:
from IPython.core.interactiveshell import InteractiveShell
shell = InteractiveShell()
result = shell.run_cell("...above code of the cell here...")
# result either gives an error when using %matplotlib inline or retrieves
# no useful info if no line magic is present
Problem is that InteractiveShell instance will not accept the %matplotlib inline magic, giving a NotImplementedError in its enable_gui method which is, wll, not implemented. I found very few information about this apart from a single issue on IPython's Github.
I know I can do this manually by using plt.save() but that doesn't seem right to me as I don't want to write manual interpretations each time I need another rich representation of the result. I feel like I'm missing a lot here in the way IPython works, so I'm asking for help in retrieving the results. What exactly does Jupyter Notebook do to retrieve the rich representation and perhaps can it be done painlessly via other means? I'm looking at using jupyter_client but for now that seems to be even more confusing.
UPDATE:
The io.capture_output context manager seems to be the way to go but I've been able to capture string outputs only (pretty much the same as using %%capture cell magic):
with io.capture_output() as captured:
result = shell.run_cell(cell)
#captures strings only:
captured.stdout = {str} '<matplotlib.figure.Figure at 0x4f486d8>'

Pandas plot doesn't show

When using this in a script (not IPython), nothing happens, i.e. the plot window doesn't appear :
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
Even when adding time.sleep(5), there is still nothing. Why?
Is there a way to do it, without having to manually call matplotlib ?
Once you have made your plot, you need to tell matplotlib to show it. The usual way to do things is to import matplotlib.pyplot and call show from there:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
plt.show()
In older versions of pandas, you were able to find a backdoor to matplotlib, as in the example below. NOTE: This no longer works in modern versions of pandas, and I still recommend importing matplotlib separately, as in the example above.
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
pd.tseries.plotting.pylab.show()
But all you are doing there is finding somewhere that matplotlib has been imported in pandas, and calling the same show function from there.
Are you trying to avoid calling matplotlib in an effort to speed things up? If so then you are really not speeding anything up, since pandas already imports pyplot:
python -mtimeit -s 'import pandas as pd'
100000000 loops, best of 3: 0.0122 usec per loop
python -mtimeit -s 'import pandas as pd; import matplotlib.pyplot as plt'
100000000 loops, best of 3: 0.0125 usec per loop
Finally, the reason the example you linked in comments doesn't need the call to matplotlib is because it is being run interactively in an iPython notebook, not in a script.
In case you are using matplotlib, and still, things don't show up in iPython notebook (or Jupyter Lab as well) remember to set the inline option for matplotlib in the notebook.
import matplotlib.pyplot as plt
%matplotlib inline
Then the following code will work flawlessly:
fig, ax = plt.subplots(figsize=(16,9));
change_per_ins.plot(ax=ax, kind='hist')
If you don't set the inline option it won't show up and by adding a plt.show() in the end you will get duplicate outputs.
I did just
import matplotlib.pyplot as plt
%matplotlib inline
and add line
plt.show()
next to df.plot() and it worked well for
The other answers involve importing matplotlib.pyplot and/or calling some second function manually.
Instead, you can configure matplotlib to be in interactive mode with its configuration files.
Simply add the line
interactive: True
to a file called matplotlibrc in one of the following places:
In the current working directory
In the platform specific user directory specified by matplotlib.get_configdir()
On unix-like system, typically /home/username/.config/matplotlib/
On Windows C:\\Documents and Settings\\username\\.matplotlib\\

Categories

Resources