20. Visualization

Visualization

We use the standard convention for referencing the matplotlib API:

In [1]: import matplotlib.pyplot as plt

The plots in this document are made using matplotlib’s ggplot style (new in version 1.4):

import matplotlib
matplotlib.style.use('ggplot')

We provide the basics in pandas to easily create decent looking plots. See the ecosystem section for visualization libraries that go beyond the basics documented here.

Note

All calls to np.random are seeded with 123456.

Basic Plotting: plot

See the cookbook for some advanced strategies

The plot method on Series and DataFrame is just a simple wrapper around plt.plot():

In [2]: ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))

In [3]: ts = ts.cumsum()

In [4]: ts.plot()
Out[4]: <matplotlib.axes._subplots.AxesSubplot at 0x13ada0518>
_images/series_plot_basic.png

If the index consists of dates, it calls gcf().autofmt_xdate() to try to format the x-axis nicely as per above.

On DataFrame, plot() is a convenience to plot all of the columns with labels:

In [5]: df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))

In [6]: df = df.cumsum()

In [7]: plt.figure(); df.plot();
_images/frame_plot_basic.png

You can plot one column versus another using the x and y keywords in plot():

In [8]: df3 = pd.DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()

In [9]: df3['A'] = pd.Series(list(range(len(df))))

In [10]: df3.plot(x='A', y='B')
Out[10]: <matplotlib.axes._subplots.AxesSubplot at 0x136e544a8>
_images/df_plot_xy.png

Note

For more formatting and styling options, see below.

Other Plots

Plotting methods allow for a handful of plot styles other than the default Line plot. These methods can be provided as the kind keyword argument to plot(). These include:

For example, a bar plot can be created the following way:

In [11]: plt.figure();

In [12]: df.iloc[5].plot(kind='bar'); plt.axhline(0, color='k')
Out[12]: <matplotlib.lines.Line2D at 0x136909c50>
_images/bar_plot_ex.png

New in version 0.17.0.

You can also create these other plots using the methods DataFrame.plot.<kind> instead of providing the kind keyword argument. This makes it easier to discover plot methods and the specific arguments they use:

In [13]: df = pd.DataFrame()

In [14]: df.plot.<TAB>
df.plot.area     df.plot.barh     df.plot.density  df.plot.hist     df.plot.line     df.plot.scatter
df.plot.bar      df.plot.box      df.plot.hexbin   df.plot.kde      df.plot.pie

In addition to these kind s, there are the DataFrame.hist(), and DataFrame.boxplot() methods, which use a separate interface.

Finally, there are several plotting functions in pandas.plotting that take a Series or DataFrame as an argument. These include

Plots may also be adorned with errorbars or tables.

Bar plots

For labeled, non-time series data, you may wish to produce a bar plot:

In [15]: plt.figure();

In [16]: df.iloc[5].plot.bar(); plt.axhline(0, color='k')
Out[16]: <matplotlib.lines.Line2D at 0x13692e470>
_images/bar_plot_ex.png

Calling a DataFrame’s plot.bar() method produces a multiple bar plot:

In [17]: df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])

In [18]: df2.plot.bar();
_images/bar_plot_multi_ex.png

To produce a stacked bar plot, pass stacked=True:

In [19]: df2.plot.bar(stacked=True);
_images/bar_plot_stacked_ex.png

To get horizontal bar plots, use the barh method:

In [20]: df2.plot.barh(stacked=True);
_images/barh_plot_stacked_ex.png

Histograms

New in version 0.15.0.

Histogram can be drawn by using the DataFrame.plot.hist() and Series.plot.hist() methods.

In [21]: df4 = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
   ....:                     'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c'])
   ....: 

In [22]: plt.figure();

In [23]: df4.plot.hist(alpha=0.5)
Out[23]: <matplotlib.axes._subplots.AxesSubplot at 0x13a4b6710>
_images/hist_new.png

Histogram can be stacked by stacked=True. Bin size can be changed by bins keyword.

In [24]: plt.figure();

In [25]: df4.plot.hist(stacked=True, bins=20)
Out[25]: <matplotlib.axes._subplots.AxesSubplot at 0x13de89da0>
_images/hist_new_stacked.png

You can pass other keywords supported by matplotlib hist. For example, horizontal and cumulative histgram can be drawn by orientation='horizontal' and cumulative='True'.

In [26]: plt.figure();

In [27]: df4['a'].plot.hist(orientation='horizontal', cumulative=True)
Out[27]: <matplotlib.axes._subplots.AxesSubplot at 0x13e38aba8>
_images/hist_new_kwargs.png

See the hist method and the matplotlib hist documentation for more.

The existing interface DataFrame.hist to plot histogram still can be used.

In [28]: plt.figure();

In [29]: df['A'].diff().hist()
Out[29]: <matplotlib.axes._subplots.AxesSubplot at 0x13cdbbba8>
_images/hist_plot_ex.png

DataFrame.hist() plots the histograms of the columns on multiple subplots:

In [30]: plt.figure()
Out[30]: <matplotlib.figure.Figure at 0x13de652e8>

In [31]: df.diff().hist(color='k', alpha=0.5, bins=50)

© 2008–2012, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
Licensed under the 3-clause BSD License.
http://pandas.pydata.org/pandas-docs/version/0.20.2/visualization.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部