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

Question:

I am aware that pandas offer the opportunity to visualize data with plots. Most of the examples I can find and even pandas docu itself use Jupyter Notebook examples.

This code doesn’t work in a row python shell.

#!/usr/bin/env python3
import pandas as pd

df = pd.DataFrame({'A': range(100)})

obj = df.hist(column='A')
# array([[<AxesSubplot:title={'center':'A'}>]], dtype=object)

How can I "show" that?
This scripts runs not in an IDE. It runs in a Python 3.9.10 shell interpreter in Windows "Dos-Box" on Windows 10.

Installing jupyter or transfering the data to an external service is not an option in my case.

Asked By: buhtz

||

Answers:

Try something like this

df = pd.DataFrame({'A': list(range(100))})

df.plot(kind='line')
Answered By: Esa Tuulari

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.)

Answered By: Wayne
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.