This question already has answers here:
prevent plot from showing in jupyter notebook
(7 answers)
How to prevent matplotlib from to showing a figure even with plt.close() in jupyter notebook
(1 answer)
Closed 9 months ago.
I like to only show a matplotlib figure with an explicit show(fig). But Jupyter automatically shows all created figures.
This link has a workaround, but it is essentially just capturing all the output of a cell. I don't want to do that.
Related:
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.show.html#:~:text=auto-show%20in%20jupyter%20notebooks
PS: I am actually using seaborn, not matplotlib directly.
Using plt.ioff disables interactive mode and storing figure in a variable won't display any output:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
plt.ioff()
sns.set_theme(style="darkgrid")
# Load an example dataset with long-form data
fmri = sns.load_dataset("fmri")
# Plot the responses for different events and regions
fig = sns.lineplot(x="timepoint", y="signal",
hue="region", style="event",
data=fmri)
But using plt.show() reverses the effect and show the output figure:
# Import modules here
plt.ioff()
# Set theme and load data here
fig = sns.lineplot(x="timepoint", y="signal",
hue="region", style="event",
data=fmri)
plt.show()
How the Jupyter Notebook output looks like when the above code is used:
The code for plotting the Timeseries plot comes from here.
Related
I have written the code below to plot multiple figures using FacetGrid of seaborn ( sns.lmplot ). Saving figure in pdf format will result in a 1 page pdf file. I was wondering if someone could help me to have only like 3 rows and 4 columns per page and also have them all plotted in a single pdf with multiple pages?
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
g = sns.lmplot('index','value',data=merged, col="station", hue="flow type",col_wrap=3,height=2,aspect=2,legend_out=False,fit_reg=False,sharex=False,sharey=False)
#g.savefig('50%_flow_duration_curves_cariboo.pdf', format='png', dpi=1000)
g.set_xlabels("exceedence %")
g.set_ylabels("flow")
here is how it looks like now:
I created a figure which has 2 axes, how can I plot specific axes(eg,ax[0]) rather than plot both axes? When I input fig in the end both axes will appear together. What code should I write if I just want ax[0] be displayed for example?
fig,ax=plt.subplots(2)
x=np.linspace(1,10,100)
ax[0].plot(x,np.sin(x))
ax[1].plot(x,np.cos(x))
fig
I interprete that you are using Jupyter notebook. You may then use the fact that invisble axes parts of a figure will be cropped with the matplotlib inline backend.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig,ax=plt.subplots(2);
x=np.linspace(1,10,100)
ax[0].plot(x,np.sin(x))
ax[1].plot(x,np.cos(x))
Now to only show the second subplot, you can set the first invisible,
ax[0].set_visible(False)
fig
If you then want to only show the first subplot, you need to set it visible again and the second one invisible
ax[0].set_visible(True)
ax[1].set_visible(False)
fig
This question already has answers here:
Matplotlib and Ipython-notebook: Displaying exactly the figure that will be saved
(2 answers)
Closed 4 years ago.
I want to make a square plot with matplotlib. That is, I want the whole figure to be square. When I use the following code, the width of the resulting image is still a bit larger than the height. Why is matplotlib not respecting the figsize I provide?
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 10))
# When inspecting in browser, reveals 611x580 px image
ax.plot([1,2,3], [1,2,3])
Edit: I display the image inline in a Jupyter notebook, and just use the Chrome developer tools to inspect the image.
That is a problem of jupyter notebook. The figure it shows is a "saved" version, which uses the bbox_inches="tight" option and hence changes the size of the shown image.
One option you have is to save the figure manually to png,
fig.savefig("output.png")
As #EvgenyPogrebnyak commented, the other option is to deactivate the "tight" option in the notebook as
%matplotlib inline
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
fig, ax = plt.subplots(figsize=(10, 10))
# When inspecting in browser,
ax.plot([1,2,3], [1,2,3]) # now reveals 720 x 720 px image
as seen in this answer.
I am new to matplotlib and seaborn and is currently trying to practice the two libraries using the classic titanic dataset. This might be elementary, but I'm trying to plot two factorplots side by side by inputting the argument ax = matplotlib axis as shown in the code below:
import matploblib.pyplot as plt
import seaborn as sns
%matplotlib inline
fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='Pclass',data=titanic_df,kind='count',hue='Survived',ax=axis1)
sns.factorplot(x='SibSp',data=titanic_df,kind='count',hue='Survived',ax=axis2)
I was expecting the two factorplots side by side, but instead of just that, I ended up with two extra blank subplots as shown above
Edited: image was not there
Any call to sns.factorplot() actually creates a new figure, although the contents are drawn to the existing axes (axes1, axes2). Those figures are shown together with the original fig.
I guess the easiest way to prevent those unused figures from showing up is to close them, using plt.close(<figure number>).
Here is a solution for a notebook
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
%matplotlib inline
titanic_df = pd.read_csv(r"https://github.com/pcsanwald/kaggle-titanic/raw/master/train.csv")
fig, (axis1,axis2) = plt.subplots(1,2,figsize=(15,4))
sns.factorplot(x='pclass',data=titanic_df,kind='count',hue='survived',ax=axis1)
sns.factorplot(x='sibsp',data=titanic_df,kind='count',hue='survived',ax=axis2)
plt.close(2)
plt.close(3)
(For normal console plotting, remove the %matplotlib inline command and add plt.show() at the end.)
I am trying to generate the log-log plot of a vector, and save the generated plot to file.
This is what I have tried so far:
import matplotlib.pyplot as plt
...
plt.loglog(deg_distribution,'b-',marker='o')
plt.savefig('LogLog.png')
I am using Jupyter Notebook, in which I get the generated graph as output after statement 2 in the above code, but the saved file is blank.
Notice that pyplot has the concept of the current figure and the current axes. All plotting commands apply to the current axes. So, make sure you plot in the right axes. Here is a WME.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.loglog(range(100), 'b-',marker='o')
plt.savefig('test.png') # apply to the axes `ax`