Saving Plots (Axessubplot) Generated from Python Pandas with Matplotlib's Savefig

How to save image created with 'pandas.DataFrame.plot'?

Try this :

fig = class_counts.plot(kind='bar',  
figsize=(20, 16), fontsize=26).get_figure()

fig.savefig('test.pdf')

How to plot with (raw) pandas and without Jupyter notebook

Demonstrating a solution building on code provided by OP:

Save this as a script named save_test.py in your working directory:

import pandas as pd
df = pd.DataFrame({'A': range(100)})
the_plot_array = df.hist(column='A')
fig = the_plot_array [0][0].get_figure()
fig.savefig("output.png")

Run that script on command line using python save_test.py.

You should see it create a file called output.png in your working directory. Open the generated image with your favorite image file viewer on your machine. If you are doing this remote, download the image file and view on your local machine.

You should also be able to run those lines in succession in a interpreter if the OP prefers.

Explanation:

Solution provided based on the fact Pandas plotting uses matplotlib as the default plotting backend (which can be changed), so you can use Matplotlib's ability to save generated plots as images, combined with Wael Ben Zid El Guebsi's answer to 'Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig' and using type() to drill down to see that pandas histogram is returned as an numpy array of arrays. (The first item in the inner array is an matplotlib.axes._subplots.AxesSubplot object, that the_plot_array [0][0] gets. The get_figure() method gets the plot from that matplotlib.axes._subplots.AxesSubplot object.)

Save pandas.DataFrame.hist with multiple axes in one figure

savefig is not a method of the plot object returned by the df.hist. Try the following

import matplotlib.pyplot as plt

# rest of your code

plot = df.hist(figsize = (20, 15))
plt.savefig(os.path.join(folder_wd, folder_output, folder_dataset,'histogram.png'))

problem with saving the plot savefig in python

Your table.plot returns a matplotlib.pyplot.axes object.

table=pd.DataFrame(ycon[att[0]])        
table[att[0]]=pd.to_numeric(table[att[0]],downcast='float',errors='coerce')
ax = table.plot()
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

Saving Colorbar Plot as Image File

I figured it out. Not sure why this works and what I did earlier didn't work. I think it had something to do with how Jupyter notebook displays things. But anyways here's what I did:

plt.scatter(X,Y,c=Z, cmap='gnuplot2')
clb = plt.colorbar()
clb.set_label('label')
plt.savefig('name.jpg') #this saves all of what is shown below
plt.show()


Related Topics



Leave a reply



Submit