Forums

Pandas plotting in IPython

How to save a plot from Pandas in Ipython? (Not exactly the same as from the matplotlib example PythonAnywhere gives.) Any thoughts? Can give example if it would help.

Maybe another way to ask my question is that the object PythonAnywhere's example works for is a matplotlib.figure.Figure as produced by your example:
''' import matplotlib import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))

fig.savefig('graph.png')

graph.png will then show up in your home directory. Simply put, wherever you might normally use plt.show() to display your graph on screen you should use fig.savefig('your_graph.png') to save it as an image file instead.

Once you've done that, you can view the graph from your browser using a URL like this: http://www.pythonanywhere.com/user/your-username/files/home/your-username/graph.png '''

While the object Pandas produces is a matplotlib.axes.AxesSubplot (which does not seem to have a savefig attribute) as produced by this example from Wes McKinney's 'Python for DataAnalysis':
''' Time Series Plotting Plots with pandas time series have improved date formatting compared with matplotlib out of the box. As an example, I downloaded some stock price data on a few common US stock from Yahoo! Finance: In [539]: close_px_all = pd.read_csv('ch09/stock_px.csv', parse_dates=True, index_col=0)

In [540]: close_px = close_px_all[['AAPL', 'MSFT', 'XOM']]

In [541]: close_px = close_px.resample('B', fill_method='ffill')

In [542]: close_px
Out[542]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2292 entries, 2003-01-02 00:00:00 to 2011-10-14 00:00:00
Freq: B
Data columns:
AAPL    2292 non-null values
MSFT    2292 non-null values
XOM     2292 non-null values
dtypes: float64(3)

Calling plot on one of the columns grenerates a simple plot, seen in Figure 10-4. In [544]: close_px['AAPL'].plot() '''

Doing something like fig=close_px['AAPL'].plot() works, but, then doing something like fig.savefig('graph.png') gets you 'AxesSubplot' object has no attribute 'savefig'. So, it looks like you get the Pandas plot, but, how do you get it saved somewhere so it may be viewed using PythonAnywhere?

Thanks.

Sorry. Something happened to the formatting. Think it's still understandable, though.

Without knowing pandas and the example have you tried using savefig from matplotlib.pyplot?

You knew enough. Thank you.

I love it when a plan comes together!!...☺

I ran into the same problem - see my StackOverflow post here:

The short solution is something like this:

ax = pandas.DataFrame.from_records(d,columns=h)
ax.plot()
fig = matplotlib.pyplot.gcf()
fig.savefig('graph.png')