0
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.
eugene
  • 39,839
  • 68
  • 255
  • 489
  • Your question has been answered here. Please have a look: https://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it-using-matplotlib – Mighty Diffy Dec 02 '20 at 02:31
  • I don't get how I can draw using `df.plot.bar() ` without `show` .. the questions is about `fig.plot()` which may be same thing internally, but I can't decypher what to do.. – eugene Dec 02 '20 at 02:36

1 Answers1

0

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)
meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34