Plotting with matplotlib¶
Note
We intend to build more plotting integration with matplotlib as time goes on.
We use the standard convention for referencing the matplotlib API:
In [1723]: import matplotlib.pyplot as plt
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 [1724]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
In [1725]: ts = ts.cumsum()
In [1726]: ts.plot()
Out[1726]: <matplotlib.axes.AxesSubplot at 0x122e2cd0>
![_images/series_plot_basic.png](_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. The method takes a number of arguments for controlling the look of the plot:
In [1727]: plt.figure(); ts.plot(style='k--', label='Series'); plt.legend()
Out[1727]: <matplotlib.legend.Legend at 0x11f84d50>
![_images/series_plot_basic2.png](_images/series_plot_basic2.png)
On DataFrame, plot is a convenience to plot all of the columns with labels:
In [1728]: df = DataFrame(randn(1000, 4), index=ts.index,
......: columns=['A', 'B', 'C', 'D'])
......:
In [1729]: df = df.cumsum()
In [1730]: plt.figure(); df.plot(); plt.legend(loc='best')
Out[1730]: <matplotlib.legend.Legend at 0x12e28410>
![_images/frame_plot_basic.png](_images/frame_plot_basic.png)
You may set the legend argument to False to hide the legend, which is shown by default.
In [1731]: df.plot(legend=False)
Out[1731]: <matplotlib.axes.AxesSubplot at 0xd7b4710>
![_images/frame_plot_basic_noleg.png](_images/frame_plot_basic_noleg.png)
Some other options are available, like plotting each Series on a different axis:
In [1732]: df.plot(subplots=True, figsize=(6, 6)); plt.legend(loc='best')
Out[1732]: <matplotlib.legend.Legend at 0xc753f50>
![_images/frame_plot_subplots.png](_images/frame_plot_subplots.png)
You may pass logy to get a log-scale Y axis.
In [1733]: plt.figure();
In [1733]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
In [1734]: ts = np.exp(ts.cumsum())
In [1735]: ts.plot(logy=True)
Out[1735]: <matplotlib.axes.AxesSubplot at 0x8dbd850>
![_images/series_plot_logy.png](_images/series_plot_logy.png)
You can plot one column versus another using the x and y keywords in DataFrame.plot:
In [1736]: plt.figure()
Out[1736]: <matplotlib.figure.Figure at 0xd7a3650>
In [1737]: df3 = DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
In [1738]: df3['A'] = Series(range(len(df)))
In [1739]: df3.plot(x='A', y='B')
Out[1739]: <matplotlib.axes.AxesSubplot at 0x688a250>
![_images/df_plot_xy.png](_images/df_plot_xy.png)
Plotting on a Secondary Y-axis¶
To plot data on a secondary y-axis, use the secondary_y keyword:
In [1740]: plt.figure()
Out[1740]: <matplotlib.figure.Figure at 0x7ee3b10>
In [1741]: df.A.plot()
Out[1741]: <matplotlib.axes.AxesSubplot at 0x7634110>
In [1742]: df.B.plot(secondary_y=True, style='g')
Out[1742]: <matplotlib.axes.AxesSubplot at 0x6288c50>
![_images/series_plot_secondary_y.png](_images/series_plot_secondary_y.png)
Selective Plotting on Secondary Y-axis¶
To plot some columns in a DataFrame, give the column names to the secondary_y keyword:
In [1743]: plt.figure()
Out[1743]: <matplotlib.figure.Figure at 0xf4982d0>
In [1744]: ax = df.plot(secondary_y=['A', 'B'])
In [1745]: ax.set_ylabel('CD scale')
Out[1745]: <matplotlib.text.Text at 0xeb50e50>
In [1746]: ax.right_ax.set_ylabel('AB scale')
Out[1746]: <matplotlib.text.Text at 0x6e74210>
![_images/frame_plot_secondary_y.png](_images/frame_plot_secondary_y.png)
Note that the columns plotted on the secondary y-axis is automatically marked with “(right)” in the legend. To turn off the automatic marking, use the mark_right=False keyword:
In [1747]: plt.figure()
Out[1747]: <matplotlib.figure.Figure at 0x7d383d0>
In [1748]: df.plot(secondary_y=['A', 'B'], mark_right=False)
Out[1748]: <matplotlib.axes.AxesSubplot at 0x66cb110>
![_images/frame_plot_secondary_y_no_right.png](_images/frame_plot_secondary_y_no_right.png)
Suppressing tick resolution adjustment¶
Pandas includes automatically tick resolution adjustment for regular frequency time-series data. For limited cases where pandas cannot infer the frequency information (e.g., in an externally created twinx), you can choose to suppress this behavior for alignment purposes.
Here is the default behavior, notice how the x-axis tick labelling is performed:
In [1749]: plt.figure()
Out[1749]: <matplotlib.figure.Figure at 0x7d2b690>
In [1750]: df.A.plot()
Out[1750]: <matplotlib.axes.AxesSubplot at 0x7d2b510>
![_images/ser_plot_suppress.png](_images/ser_plot_suppress.png)
Using the x_compat parameter, you can suppress this bevahior:
In [1751]: plt.figure()
Out[1751]: <matplotlib.figure.Figure at 0x97907d0>
In [1752]: df.A.plot(x_compat=True)
Out[1752]: <matplotlib.axes.AxesSubplot at 0x8dd1e50>
![_images/ser_plot_suppress_parm.png](_images/ser_plot_suppress_parm.png)
If you have more than one plot that needs to be suppressed, the use method in pandas.plot_params can be used in a with statement:
In [1753]: import pandas as pd
In [1754]: plt.figure()
Out[1754]: <matplotlib.figure.Figure at 0xe9d4e10>
In [1755]: with pd.plot_params.use('x_compat', True):
......: df.A.plot(color='r')
......: df.B.plot(color='g')
......: df.C.plot(color='b')
......:
![_images/ser_plot_suppress_context.png](_images/ser_plot_suppress_context.png)
Targeting different subplots¶
You can pass an ax argument to Series.plot to plot on a particular axis:
In [1756]: fig, axes = plt.subplots(nrows=2, ncols=2)
In [1757]: df['A'].plot(ax=axes[0,0]); axes[0,0].set_title('A')
Out[1757]: <matplotlib.text.Text at 0x84bc810>
In [1758]: df['B'].plot(ax=axes[0,1]); axes[0,1].set_title('B')
Out[1758]: <matplotlib.text.Text at 0x135dfed0>
In [1759]: df['C'].plot(ax=axes[1,0]); axes[1,0].set_title('C')
Out[1759]: <matplotlib.text.Text at 0x87cf490>
In [1760]: df['D'].plot(ax=axes[1,1]); axes[1,1].set_title('D')
Out[1760]: <matplotlib.text.Text at 0xff5a990>
![_images/series_plot_multi.png](_images/series_plot_multi.png)
Other plotting features¶
Bar plots¶
For labeled, non-time series data, you may wish to produce a bar plot:
In [1761]: plt.figure();
In [1761]: df.ix[5].plot(kind='bar'); plt.axhline(0, color='k')
Out[1761]: <matplotlib.lines.Line2D at 0x12651110>
![_images/bar_plot_ex.png](_images/bar_plot_ex.png)
Calling a DataFrame’s plot method with kind='bar' produces a multiple bar plot:
In [1762]: df2 = DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
In [1763]: df2.plot(kind='bar');
![_images/bar_plot_multi_ex.png](_images/bar_plot_multi_ex.png)
To produce a stacked bar plot, pass stacked=True:
In [1763]: df2.plot(kind='bar', stacked=True);
![_images/bar_plot_stacked_ex.png](_images/bar_plot_stacked_ex.png)
To get horizontal bar plots, pass kind='barh':
In [1763]: df2.plot(kind='barh', stacked=True);
![_images/barh_plot_stacked_ex.png](_images/barh_plot_stacked_ex.png)
Histograms¶
In [1763]: plt.figure();
In [1763]: df['A'].diff().hist()
Out[1763]: <matplotlib.axes.AxesSubplot at 0x12b80ad0>
![_images/hist_plot_ex.png](_images/hist_plot_ex.png)
For a DataFrame, hist plots the histograms of the columns on multiple subplots:
In [1764]: plt.figure()
Out[1764]: <matplotlib.figure.Figure at 0x12b74d90>
In [1765]: df.diff().hist(color='k', alpha=0.5, bins=50)
Out[1765]:
array([[<matplotlib.axes.AxesSubplot object at 0x12cbbf10>,
<matplotlib.axes.AxesSubplot object at 0x12ce9fd0>],
[<matplotlib.axes.AxesSubplot object at 0x10a51f90>,
<matplotlib.axes.AxesSubplot object at 0x10a73dd0>]], dtype=object)
![_images/frame_hist_ex.png](_images/frame_hist_ex.png)
New since 0.10.0, the by keyword can be specified to plot grouped histograms:
In [1766]: data = Series(np.random.randn(1000))
In [1767]: data.hist(by=np.random.randint(0, 4, 1000))
Out[1767]:
array([[<matplotlib.axes.AxesSubplot object at 0x127c3fd0>,
<matplotlib.axes.AxesSubplot object at 0x11461a90>],
[<matplotlib.axes.AxesSubplot object at 0x12a88690>,
<matplotlib.axes.AxesSubplot object at 0x1182f510>]], dtype=object)
![_images/grouped_hist.png](_images/grouped_hist.png)
Box-Plotting¶
DataFrame has a boxplot method which allows you to visualize the distribution of values within each column.
For instance, here is a boxplot representing five trials of 10 observations of a uniform random variable on [0,1).
In [1768]: df = DataFrame(np.random.rand(10,5))
In [1769]: plt.figure();
In [1769]: bp = df.boxplot()
![_images/box_plot_ex.png](_images/box_plot_ex.png)
You can create a stratified boxplot using the by keyword argument to create groupings. For instance,
In [1770]: df = DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
In [1771]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
In [1772]: plt.figure();
In [1772]: bp = df.boxplot(by='X')
![_images/box_plot_ex2.png](_images/box_plot_ex2.png)
You can also pass a subset of columns to plot, as well as group by multiple columns:
In [1773]: df = DataFrame(np.random.rand(10,3), columns=['Col1', 'Col2', 'Col3'])
In [1774]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
In [1775]: df['Y'] = Series(['A','B','A','B','A','B','A','B','A','B'])
In [1776]: plt.figure();
In [1776]: bp = df.boxplot(column=['Col1','Col2'], by=['X','Y'])
![_images/box_plot_ex3.png](_images/box_plot_ex3.png)
Scatter plot matrix¶
- New in 0.7.3. You can create a scatter plot matrix using the
- scatter_matrix method in pandas.tools.plotting:
In [1777]: from pandas.tools.plotting import scatter_matrix
In [1778]: df = DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
In [1779]: scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
Out[1779]:
array([[<matplotlib.axes.AxesSubplot object at 0x15479f50>,
<matplotlib.axes.AxesSubplot object at 0x1575e950>,
<matplotlib.axes.AxesSubplot object at 0x158c5510>,
<matplotlib.axes.AxesSubplot object at 0x158e9d50>],
[<matplotlib.axes.AxesSubplot object at 0x15a1fa90>,
<matplotlib.axes.AxesSubplot object at 0x15b78650>,
<matplotlib.axes.AxesSubplot object at 0x15b9d490>,
<matplotlib.axes.AxesSubplot object at 0x15a2be10>],
[<matplotlib.axes.AxesSubplot object at 0x15d2ed10>,
<matplotlib.axes.AxesSubplot object at 0x15e99710>,
<matplotlib.axes.AxesSubplot object at 0x14ee1890>,
<matplotlib.axes.AxesSubplot object at 0x15ff21d0>],
[<matplotlib.axes.AxesSubplot object at 0x16016810>,
<matplotlib.axes.AxesSubplot object at 0x1617ddd0>,
<matplotlib.axes.AxesSubplot object at 0x161a5550>,
<matplotlib.axes.AxesSubplot object at 0x1618a3d0>]], dtype=object)
![_images/scatter_matrix_kde.png](_images/scatter_matrix_kde.png)
New in 0.8.0 You can create density plots using the Series/DataFrame.plot and setting kind=’kde’:
In [1780]: ser = Series(np.random.randn(1000))
In [1781]: ser.plot(kind='kde')
Out[1781]: <matplotlib.axes.AxesSubplot at 0x16bb5950>
![_images/kde_plot.png](_images/kde_plot.png)
Andrews Curves¶
Andrews curves allow one to plot multivariate data as a large number of curves that are created using the attributes of samples as coefficients for Fourier series. By coloring these curves differently for each class it is possible to visualize data clustering. Curves belonging to samples of the same class will usually be closer together and form larger structures.
Note: The “Iris” dataset is available here.
In [1782]: from pandas import read_csv
In [1783]: from pandas.tools.plotting import andrews_curves
In [1784]: data = read_csv('data/iris.data')
In [1785]: plt.figure()
Out[1785]: <matplotlib.figure.Figure at 0x16cd7990>
In [1786]: andrews_curves(data, 'Name')
Out[1786]: <matplotlib.axes.AxesSubplot at 0x16cd7850>
![_images/andrews_curves.png](_images/andrews_curves.png)
Parallel Coordinates¶
Parallel coordinates is a plotting technique for plotting multivariate data. It allows one to see clusters in data and to estimate other statistics visually. Using parallel coordinates points are represented as connected line segments. Each vertical line represents one attribute. One set of connected line segments represents one data point. Points that tend to cluster will appear closer together.
In [1787]: from pandas import read_csv
In [1788]: from pandas.tools.plotting import parallel_coordinates
In [1789]: data = read_csv('data/iris.data')
In [1790]: plt.figure()
Out[1790]: <matplotlib.figure.Figure at 0x16cd78d0>
In [1791]: parallel_coordinates(data, 'Name')
Out[1791]: <matplotlib.axes.AxesSubplot at 0x176b5d50>
![_images/parallel_coordinates.png](_images/parallel_coordinates.png)
Lag Plot¶
Lag plots are used to check if a data set or time series is random. Random data should not exhibit any structure in the lag plot. Non-random structure implies that the underlying data are not random.
In [1792]: from pandas.tools.plotting import lag_plot
In [1793]: plt.figure()
Out[1793]: <matplotlib.figure.Figure at 0x18006390>
In [1794]: data = Series(0.1 * np.random.random(1000) +
......: 0.9 * np.sin(np.linspace(-99 * np.pi, 99 * np.pi, num=1000)))
......:
In [1795]: lag_plot(data)
Out[1795]: <matplotlib.axes.AxesSubplot at 0x18006f10>
![_images/lag_plot.png](_images/lag_plot.png)
Autocorrelation Plot¶
Autocorrelation plots are often used for checking randomness in time series. This is done by computing autocorrelations for data values at varying time lags. If time series is random, such autocorrelations should be near zero for any and all time-lag separations. If time series is non-random then one or more of the autocorrelations will be significantly non-zero. The horizontal lines displayed in the plot correspond to 95% and 99% confidence bands. The dashed line is 99% confidence band.
In [1796]: from pandas.tools.plotting import autocorrelation_plot
In [1797]: plt.figure()
Out[1797]: <matplotlib.figure.Figure at 0x17ee3c90>
In [1798]: data = Series(0.7 * np.random.random(1000) +
......: 0.3 * np.sin(np.linspace(-9 * np.pi, 9 * np.pi, num=1000)))
......:
In [1799]: autocorrelation_plot(data)
Out[1799]: <matplotlib.axes.AxesSubplot at 0x17ed56d0>
![_images/autocorrelation_plot.png](_images/autocorrelation_plot.png)
Bootstrap Plot¶
Bootstrap plots are used to visually assess the uncertainty of a statistic, such as mean, median, midrange, etc. A random subset of a specified size is selected from a data set, the statistic in question is computed for this subset and the process is repeated a specified number of times. Resulting plots and histograms are what constitutes the bootstrap plot.
In [1800]: from pandas.tools.plotting import bootstrap_plot
In [1801]: data = Series(np.random.random(1000))
In [1802]: bootstrap_plot(data, size=50, samples=500, color='grey')
Out[1802]: <matplotlib.figure.Figure at 0x182aaed0>
![_images/bootstrap_plot.png](_images/bootstrap_plot.png)
RadViz¶
RadViz is a way of visualizing multi-variate data. It is based on a simple spring tension minimization algorithm. Basically you set up a bunch of points in a plane. In our case they are equally spaced on a unit circle. Each point represents a single attribute. You then pretend that each sample in the data set is attached to each of these points by a spring, the stiffness of which is proportional to the numerical value of that attribute (they are normalized to unit interval). The point in the plane, where our sample settles to (where the forces acting on our sample are at an equilibrium) is where a dot representing our sample will be drawn. Depending on which class that sample belongs it will be colored differently.
Note: The “Iris” dataset is available here.
In [1803]: from pandas import read_csv
In [1804]: from pandas.tools.plotting import radviz
In [1805]: data = read_csv('data/iris.data')
In [1806]: plt.figure()
Out[1806]: <matplotlib.figure.Figure at 0x16004c50>
In [1807]: radviz(data, 'Name')
Out[1807]: <matplotlib.axes.AxesSubplot at 0x18973610>
![_images/radviz.png](_images/radviz.png)