Matplotlib, prevent plot from showing - python

df_rm_count[['count']].sort_values(by='count', ascending=False).plot.barh()
The above line shows the graph (without plt.show())
I'd like to save the plot as image but can't because plot immediately displays the plot
I tried
%matplotlib (to negate %matplotlib inline I get ModuleNotFoundError: No module named '_tkinter' error)
plt.ioff()
plt.close('all')
matplotlib.pyplot.close(fig)
matplotlib.interactive(False)
none of the above worked..
edit
Agg didn't work either..
import matplotlib as mpl
mpl.use('Agg')
ipykernel_launcher.py:2: UserWarning: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called
*before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time.

You can use a different backend that cannot display a figure, for example Agg
import matplotlib as mpl
mpl.use('Agg')
In order to not restart the kernel, put plt.switch_backend('Agg') right below the lines that create fig and ax, for example
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111)
plt.switch_backend('Agg')
df = pd.DataFrame()
df['a'] = [1,2,3]
df['a'].plot.barh(ax=ax)

Related

Matplotlib FuncAnimation not plotting any chart inside Jupyter Notebook

Simple matplotlib plot. Here is my code
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from itertools import count
import random
x = []
y = []
index=count()
def animate(i):
x.append(next(index))
y.append(random.randint(0,10))
plt.plot(x,y)
a = FuncAnimation(plt.gcf(),animate,interval=1000)
plt.tight_layout()
plt.show()
Running the code above I get
<Figure size 576x396 with 0 Axes>
but no chart appears.
Are you using Jupyter notebooks to run it? I tried with native libraries and it works just fine. The plots are visible.
Checking here i see the same situation. Could you try to use %matplotlib inline before importing matplotlib as:
%matplotlib inline # this line before importing matplotlib
from matplotlib import pyplot as plt
That said, the animation can be displayed using JavaScript. This is similar to the ani.to_html5() solution, except that it does not require any video codecs.
from IPython.display import HTML
HTML(a.to_jshtml())
this answer brings a more complete overview...

Show matplotlib figure statelessly

Here's how to create a "stateful" plot in matplotlib and show it in non-interactive mode:
import matplotlib.pyplot as plt
plt.plot([1,2,8])
plt.show()
I am more interested in the "stateless" approach as I wish to embed matplotlib in my own python library. The same plot can be constructed "statelessly" as follows:
from matplotlib.figure import Figure
fig = Figure()
ax = fig.subplots()
lines = ax.plot([1,2,8])
However I don't know how to show it without resorting to pyplot , which I don't want to do as I would like to build up my own display mechanism.
How do I show the figure without resorting to pyplot?

How to get visible bars on a histogram/distribution plot? [duplicate]

While doing some practice problems using seaborn and a Jupyter notebook, I realized that the distplot() graphs did not have the darker outlines on the individual bins that all of the sample graphs in the documentation have. I tried creating the graphs using Pycharm and noticed the same thing. Thinking it was a seaborn problem, I tried some hist() charts using matplotlib, only to get the same results.
import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset('titanic')
plt.hist(titanic['fare'], bins=30)
yielded the following graph:
Finally I stumbled across the 'edgecolor' parameter on the plt.hist() function, and setting it to black did the trick. Unfortunately I haven't found a similar parameter to use on the seaborn distplot() function, so I am still unable to get a chart that looks like it should.
I looked into changing the rcParams in matplotlib, but I have no experience with that and the following script I ran seemed to do nothing:
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 1
mpl.rcParams['lines.color'] = 'black'
mpl.rcParams['patch.linewidth'] = 1
mpl.rcParams['patch.edgecolor'] = 'black'
mpl.rcParams['axes.linewidth'] = 1
mpl.rcParams['axes.edgecolor'] = 'black'
I was just kind of guessing at the value I was supposed to change, but running my graphs again showed no changes.
I then attempted to go back to the default settings using mpl.rcdefaults()
but once again, no change.
I reinstalled matplotlib using conda but still the graphs look the same. I am running out of ideas on how to change the default edge color for these charts. I am running the latest versions of Python, matplotlib, and seaborn using the Conda build.
As part of the update to matplotlib 2.0 the edges on bar plots are turned off by default. However, you may use the rcParam
plt.rcParams["patch.force_edgecolor"] = True
to turn the edges on globally.
Probably the easiest option is to specifically set the edgecolor when creating a seaborn plot, using the hist_kws argument,
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
For matplotlib plots, you can directly use the edgecolor or ec argument.
plt.bar(x,y, edgecolor="k")
plt.hist(x, edgecolor="k")
Equally, for pandas plots,
df.plot(kind='hist',edgecolor="k")
A complete seaborn example:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.randn(100)
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
plt.show()
As of Mar, 2021 :
sns.histplot(data, edgecolor='k', linewidth=2)
work.
Using hist_kws=dict(edgecolor="k", linewidth=2) gave an error:
AttributeError: 'PolyCollection' object has no property 'hist_kws'
Using the available styles in seaborn could also solve your problem.
Available styles in seaborn are :
ticks
dark
darkgrid
white
whitegrid

No outlines on bins of Matplotlib histograms or Seaborn distplots

While doing some practice problems using seaborn and a Jupyter notebook, I realized that the distplot() graphs did not have the darker outlines on the individual bins that all of the sample graphs in the documentation have. I tried creating the graphs using Pycharm and noticed the same thing. Thinking it was a seaborn problem, I tried some hist() charts using matplotlib, only to get the same results.
import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset('titanic')
plt.hist(titanic['fare'], bins=30)
yielded the following graph:
Finally I stumbled across the 'edgecolor' parameter on the plt.hist() function, and setting it to black did the trick. Unfortunately I haven't found a similar parameter to use on the seaborn distplot() function, so I am still unable to get a chart that looks like it should.
I looked into changing the rcParams in matplotlib, but I have no experience with that and the following script I ran seemed to do nothing:
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 1
mpl.rcParams['lines.color'] = 'black'
mpl.rcParams['patch.linewidth'] = 1
mpl.rcParams['patch.edgecolor'] = 'black'
mpl.rcParams['axes.linewidth'] = 1
mpl.rcParams['axes.edgecolor'] = 'black'
I was just kind of guessing at the value I was supposed to change, but running my graphs again showed no changes.
I then attempted to go back to the default settings using mpl.rcdefaults()
but once again, no change.
I reinstalled matplotlib using conda but still the graphs look the same. I am running out of ideas on how to change the default edge color for these charts. I am running the latest versions of Python, matplotlib, and seaborn using the Conda build.
As part of the update to matplotlib 2.0 the edges on bar plots are turned off by default. However, you may use the rcParam
plt.rcParams["patch.force_edgecolor"] = True
to turn the edges on globally.
Probably the easiest option is to specifically set the edgecolor when creating a seaborn plot, using the hist_kws argument,
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
For matplotlib plots, you can directly use the edgecolor or ec argument.
plt.bar(x,y, edgecolor="k")
plt.hist(x, edgecolor="k")
Equally, for pandas plots,
df.plot(kind='hist',edgecolor="k")
A complete seaborn example:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.randn(100)
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
plt.show()
As of Mar, 2021 :
sns.histplot(data, edgecolor='k', linewidth=2)
work.
Using hist_kws=dict(edgecolor="k", linewidth=2) gave an error:
AttributeError: 'PolyCollection' object has no property 'hist_kws'
Using the available styles in seaborn could also solve your problem.
Available styles in seaborn are :
ticks
dark
darkgrid
white
whitegrid

Seaborn configuration hides default matplotlib [duplicate]

This question already has answers here:
How can I use seaborn without changing the matplotlib defaults?
(2 answers)
Closed 3 years ago.
Seaborn provides of a handful of graphics which are very interesting for scientifical data representation.
Thus I started using these Seaborn graphics interspersed with other customized matplotlib plots.
The problem is that once I do:
import seaborn as sb
This import seems to set the graphic parameters for seaborn globally and then all matplotlib graphics below the import get the seaborn parameters (they get a grey background, linewithd changes, etc, etc).
In SO there is an answer explaining how to produce seaborn plots with matplotlib configuration, but what I want is to keep the matplotlib configuration parameters unaltered when using both libraries together and at the same time be able to produce, when needed, original seaborn plots.
If you never want to use the seaborn style, but do want some of the seaborn functions, you can import seaborn using this following line (documentation):
import seaborn.apionly as sns
If you want to produce some plots with the seaborn style and some without, in the same script, you can turn the seaborn style off using the seaborn.reset_orig function.
It seems that doing the apionly import essentially sets reset_orig automatically on import, so its up to you which is most useful in your use case.
Here's an example of switching between matplotlib defaults and seaborn:
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
# a simple plot function we can reuse (taken from the seaborn tutorial)
def sinplot(flip=1):
x = np.linspace(0, 14, 100)
for i in range(1, 7):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sinplot()
# this will have the matplotlib defaults
plt.savefig('seaborn-off.png')
plt.clf()
# now import seaborn
import seaborn as sns
sinplot()
# this will have the seaborn style
plt.savefig('seaborn-on.png')
plt.clf()
# reset rc params to defaults
sns.reset_orig()
sinplot()
# this should look the same as the first plot (seaborn-off.png)
plt.savefig('seaborn-offagain.png')
which produces the following three plots:
seaborn-off.png:
seaborn-on.png:
seaborn-offagain.png:
As of seaborn version 0.8 (July 2017) the graph style is not altered anymore on import:
The default [seaborn] style is no longer applied when seaborn is imported. It is now necessary to explicitly call set() or one or more of set_style(), set_context(), and set_palette(). Correspondingly, the seaborn.apionly module has been deprecated.
You can choose the style of any plot with plt.style.use().
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn') # switch to seaborn style
# plot code
# ...
plt.style.use('default') # switches back to matplotlib style
# plot code
# ...
# to see all available styles
print(plt.style.available)
Read more about plt.style().
You may use the matplotlib.style.context functionality as described in the style guide.
#%matplotlib inline #if used in jupyter notebook
import matplotlib.pyplot as plt
import seaborn as sns
# 1st plot
with plt.style.context("seaborn-dark"):
fig, ax = plt.subplots()
ax.plot([1,2,3], label="First plot (seaborn-dark)")
# 2nd plot
with plt.style.context("default"):
fig, ax = plt.subplots()
ax.plot([3,2,1], label="Second plot (matplotlib default)")
# 3rd plot
with plt.style.context("seaborn-darkgrid"):
fig, ax = plt.subplots()
ax.plot([2,3,1], label="Third plot (seaborn-darkgrid)")
Restore all RC params to original settings (respects custom rc) is allowed by seaborn.reset_orig() function
As explained in this other question you can import seaborn with:
import seaborn.apionly as sns
And the matplotlib styles will not be modified.

Categories