Is it possible to suppress Matplotlib/Seaborn output in Jupyter notebook? - python

All - reaching out for some guidance, if any available, to help solve this somewhat frustrating issue.
I am defining a function that creates a correlation matrix using Seaborn's annotated heatmap. The function works fine, however, the Seaborn output is being produced automatically upon running the function without having to call it.
I wish to suppress this output and only produce it later on in the notebook when calling the correlation matrix, as you would do with a dataframe, other graph, etc.
Any solutions? So far, I have tried adding semi-colons, put.ioff(), different assignments to the graph/axis objects. To be honest, I am not sure if this is a Seaborn issue or one related to Matplotlib. Maybe the function could be written in an alternative way to mitigate this limitation?
Code below. Any help on this would be greatly appreciated, many thanks.
# cormat is a correlation matrix
import matplotlib.pyplot as plt
def correl_heatmap(cormat):
_f01, ax = plt.subplots(figsize=(cormat.shape[0], cormat.shape[0]));
sns.heatmap(cormat,
vmin=-1, vmax=1, center=0, square=True,
annot=True, cmap='coolwarm_r', cbar_kws={'shrink': 0.8}, ax=ax);
ax.set_xticklabels(ax.get_xticklabels(),
rotation=90,
horizontalalignment='center');
ax.set_yticklabels(ax.get_yticklabels(),
rotation=90,
verticalalignment='center');
return _f01
_f01 = correl_heatmap(cormat)
_f01

To suppress this output assign the return object a name:
_ = plt.plot(A)
or
plot(A);

Related

Understanding of fig, ax, and plt when combining Matplotlib and Pandas

I'm trying to get a better understanding of how figure, axes, and plt all fit together when combining Matplotlib and Pandas for plotting. The accepted answer here helped me connect Matplotlib and Pandas in an object oriented way I understand through this line:
fig, ax = plt.suplots()
df.plot(ax=ax)
But as I'm diving deeper the answer here threw me off. Specifically, I still have methods I need to call directly off plt, that don't apply to either a figure or an axis. Example:
fig, ax = plt.subplots()
df[['realgdp','trend']]["2000-03-31":].plot(figsize=(8,8), ax=ax)
ax.set_title('Real GDP & Trend')
ax.set_ylabel('Readl GDP')
plt.xticks(rotation=45)
If I try to call xticks(rotation=45) off ax or fig I get an error that neither ax nor fig have an xticks method. The solution I have above works, but I don't understand why.
When I type plt.xticks(rotations=45), where does that information get sent? Why does the comment in the answer here that "when you use the functions available on the module pyplot you are plotting to the 'current figure' and 'current axes'" not apply in this case? Why do I need to call off plt directly?
plt.xticks() only works on the "current" ax. You should use ax.set_xticks(), ax.set_xticklabels() and ax.tick_params() instead.
plt.xticks() is a rather old function that is still supported, mimicking similar matlab code, born in a time when people were only plotting onto a single plot. The newer functions are more general with more options.
In short: you don't need to call plt directly, you are invited to use the ax functions instead. When calling plt.xticks(), it gets rerouted to the currently active ax (often the last one created).

Python chart plot is empty

When I call:
model = doKMeans(user3, 4)
and then
ax.scatter(model.cluster_centers_[:,1], model.cluster_centers_[:,0],
s=169, c='r', marker='x', alpha=0.8, linewidths=2)
and then:
showandtell("Weekday Calls Centroids")
my chart appears empty. Any ideas why this is happening?
I believe the issue there is as simple as adding
plt.show()
to the end of your code.
Alternatively, another common mistake that might be causing that is that you if you are working on a jupyter notebook you might have forgot to add the command:
%matplotlib inline
when you import your matplotlib library
Hope that helps!

How to suppress seaborn output when recalling figure object with regplot

I am trying to plot data to a figure and respective axis in matplotlib and as new work comes up, recall the figure with the additional plot on the axis:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
x=np.arange(0,20)
y=2*x
fig,ax=plt.subplots()
ax.scatter(x,x)
ax.scatter(x,y)
fig
Which works fine with matplotlib, if I however use seaborn's regplot:
fig2,ax2=plt.subplots()
sns.regplot(x,x,ax=ax2,fit_reg=False)
sns.regplot(x,y,ax=ax2,fit_reg=False)
fig2
fig2 generates the figure that I want but the regplot command generates an empty figure. Is there a way to suppress the regplot's empty output or have it display the updated ax2 without recalling fig2?
It seems you are using the jupyter notebook with the inline backend. In some circumstances regplot triggers the creation of a new figure even if the artists are being added to the previous one and this messes up the output. I don't know why this happens but I found a workaround that might help you, using plt.ioff to temporarily disable automatic display of figures.
plt.ioff()
fig, ax = plt.subplots()
sns.regplot(x, x, ax=ax)
fig
sns.regplot(x, 2 * x, ax=ax)
fig
You have to call plt.ioff before creating the figure for this to work. After that you have to explicitly display the figure. Then you can call plt.ion to restore the default behaviour.
regplot does not generate an empty figure. According to the documentation:
Understanding the difference between regplot() and lmplot() can be a
bit tricky. In fact, they are closely related, as lmplot() uses
regplot() internally and takes most of its parameters. However,
regplot() is an axes-level function, so it draws directly onto an axes
(either the currently active axes or the one provided by the ax
parameter), while lmplot() is a figure-level function and creates its
own figure, which is managed through a FacetGrid.
When I do the following:
fig2,ax2 = plt.subplots()
same_fig2 = sns.regplot(x,x,ax=ax2,fit_reg=False)
same_fig2.figure is fig2
>>> True

How to separate one graph from the set of multiple graphs on figure

I will not be able to put the code here because it is my assignment.
My program is printing multiple graphs on one plot. Please look at the example figure on the following link: Python: Plot multiple graphs on the same figure
The link above is just an example. That is not my code nor do I have the same program. My topic is completely different. That figure is just for reference.
The line of code I am using to achieve this is: plot(a,b, label=str(meters))
What I want to do is get any one of those graph from those three curves and also plot it separately as if it is the main graph. I am doing all this inside a function, and I have created an array of numbers to loop through these different values to get three different graphs.
Do you mean something like this?
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
a = np.arange(5)
line1, = plt.plot(a, a**2) # a new figure instance is opened automatically
line2, = plt.plot(a, a**3-a)
line3, = plt.plot(a, 4*a-a**2/2.)
fig_handle = plt.figure() # Force a new figure instance to open
plt.plot(a, a**2) # This will replot 'line1', but in this new figure instance.
If not, please update your question, perhaps showing the code you already have.
Note that this is information you could find on the matplotlib pyplot tutorial.

Second y-axis label getting cut off

I'm trying to plot two sets of data in a bar graph with matplotlib, so I'm using two axes with the twinx() method. However, the second y-axis label gets cut off. I've tried a few different methods with no success (tight_layout(), setting the major_pads in rcParams, etc...). I feel like the solution is simple, but I haven't come across it yet.
Here's a MWE:
#!/usr/bin/env python
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 21})
ax = plt.gca()
plt.ylabel('Data1') #Left side
ax2 = ax.twinx()
for i in range(10):
if(i%2==0):
ax.bar(i,np.random.randint(10))
else:
ax2.bar(i,np.random.randint(1000),color='k')
plt.ylabel('Data2') #Right
side
plt.savefig("test.png")
I just figured it out: the trick is to use bbox_inches='tight' in savefig.
E.G. plt.savefig("test.png",bbox_inches='tight')
I encountered the same issue which plt.tight_layout() did not automatically solve.
Instead, I used the labelpad argument in ylabel/set_ylabel as such:
ax.set_ylabel('label here', rotation=270, color='k', labelpad=15)
I guess this was not implemented when you asked this question, but as it's the top result on google, hopefully it can help users of the current matplotlib version.

Categories

Resources