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 [1447]: import matplotlib.pyplot as plt
Basic plotting: plot¶
The plot method on Series and DataFrame is just a simple wrapper around plt.plot:
In [1448]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
In [1449]: ts = ts.cumsum()
In [1450]: ts.plot()
Out[1450]: <matplotlib.axes.AxesSubplot at 0xdb112ec>
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 [1451]: plt.figure(); ts.plot(style='k--', label='Series'); plt.legend()
Out[1451]: <matplotlib.legend.Legend at 0xdbf862c>
On DataFrame, plot is a convenience to plot all of the columns with labels:
In [1452]: df = DataFrame(randn(1000, 4), index=ts.index,
......: columns=['A', 'B', 'C', 'D'])
......:
In [1453]: df = df.cumsum()
In [1454]: plt.figure(); df.plot(); plt.legend(loc='best')
Out[1454]: <matplotlib.legend.Legend at 0xc301a6c>
You may set the legend argument to False to hide the legend, which is shown by default.
In [1455]: df.plot(legend=False)
Out[1455]: <matplotlib.axes.AxesSubplot at 0xdc4178c>
Some other options are available, like plotting each Series on a different axis:
In [1456]: df.plot(subplots=True, figsize=(8, 8)); plt.legend(loc='best')
Out[1456]: <matplotlib.legend.Legend at 0xdbac78c>
You may pass logy to get a log-scale Y axis.
In [1457]: plt.figure();
In [1457]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
In [1458]: ts = np.exp(ts.cumsum())
In [1459]: ts.plot(logy=True)
Out[1459]: <matplotlib.axes.AxesSubplot at 0xe60532c>
You can plot one column versus another using the x and y keywords in DataFrame.plot:
In [1460]: plt.figure()
Out[1460]: <matplotlib.figure.Figure at 0x8d3980c>
In [1461]: df3 = DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
In [1462]: df3['A'] = Series(range(len(df)))
In [1463]: df3.plot(x='A', y='B')
Out[1463]: <matplotlib.axes.AxesSubplot at 0xe8c0fac>
Plotting on a Secondary Y-axis¶
To plot data on a secondary y-axis, use the secondary_y keyword:
In [1464]: plt.figure()
Out[1464]: <matplotlib.figure.Figure at 0xe9f27ec>
In [1465]: df.A.plot()
Out[1465]: <matplotlib.axes.AxesSubplot at 0xe9f2c6c>
In [1466]: df.B.plot(secondary_y=True, style='g')
Out[1466]: <matplotlib.axes.AxesSubplot at 0xe9f2c6c>
Selective Plotting on Secondary Y-axis¶
To plot some columns in a DataFrame, give the column names to the secondary_y keyword:
In [1467]: plt.figure()
Out[1467]: <matplotlib.figure.Figure at 0xeab708c>
In [1468]: df.plot(secondary_y=['A', 'B'])
Out[1468]: <matplotlib.axes.AxesSubplot at 0xe8dd86c>
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 [1469]: plt.figure()
Out[1469]: <matplotlib.figure.Figure at 0xeeaa1ec>
In [1470]: df.plot(secondary_y=['A', 'B'], mark_right=False)
Out[1470]: <matplotlib.axes.AxesSubplot at 0xeeaab8c>
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 [1471]: plt.figure()
Out[1471]: <matplotlib.figure.Figure at 0xf085e4c>
In [1472]: df.A.plot()
Out[1472]: <matplotlib.axes.AxesSubplot at 0xf16a2cc>
Using the x_compat parameter, you can suppress this bevahior:
In [1473]: plt.figure()
Out[1473]: <matplotlib.figure.Figure at 0xee22fac>
In [1474]: df.A.plot(x_compat=True)
Out[1474]: <matplotlib.axes.AxesSubplot at 0xf2736cc>
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 [1475]: import pandas as pd
In [1476]: plt.figure()
Out[1476]: <matplotlib.figure.Figure at 0xf40fcec>
In [1477]: with pd.plot_params.use('x_compat', True):
......: df.A.plot(color='r')
......: df.B.plot(color='g')
......: df.C.plot(color='b')
......:
Targeting different subplots¶
You can pass an ax argument to Series.plot to plot on a particular axis:
In [1478]: fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 5))
In [1479]: df['A'].plot(ax=axes[0,0]); axes[0,0].set_title('A')
Out[1479]: <matplotlib.text.Text at 0xf5d67ac>
In [1480]: df['B'].plot(ax=axes[0,1]); axes[0,1].set_title('B')
Out[1480]: <matplotlib.text.Text at 0xf5f0c0c>
In [1481]: df['C'].plot(ax=axes[1,0]); axes[1,0].set_title('C')
Out[1481]: <matplotlib.text.Text at 0xf63162c>
In [1482]: df['D'].plot(ax=axes[1,1]); axes[1,1].set_title('D')
Out[1482]: <matplotlib.text.Text at 0xf6aa0ec>
Other plotting features¶
Bar plots¶
For labeled, non-time series data, you may wish to produce a bar plot:
In [1483]: plt.figure();
In [1483]: df.ix[5].plot(kind='bar'); plt.axhline(0, color='k')
Out[1483]: <matplotlib.lines.Line2D at 0xfb04a4c>
Calling a DataFrame’s plot method with kind='bar' produces a multiple bar plot:
In [1484]: df2 = DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
In [1485]: df2.plot(kind='bar');
To produce a stacked bar plot, pass stacked=True:
In [1485]: df2.plot(kind='bar', stacked=True);
To get horizontal bar plots, pass kind='barh':
In [1485]: df2.plot(kind='barh', stacked=True);
Histograms¶
In [1485]: plt.figure();
In [1485]: df['A'].diff().hist()
Out[1485]: <matplotlib.axes.AxesSubplot at 0xfe1554c>
For a DataFrame, hist plots the histograms of the columns on multiple subplots:
In [1486]: plt.figure()
Out[1486]: <matplotlib.figure.Figure at 0x10080dec>
In [1487]: df.diff().hist(color='k', alpha=0.5, bins=50)
Out[1487]:
array([[<matplotlib.axes.AxesSubplot object at 0x100888cc>,
<matplotlib.axes.AxesSubplot object at 0x1012dfcc>],
[<matplotlib.axes.AxesSubplot object at 0x101b204c>,
<matplotlib.axes.AxesSubplot object at 0x101cd78c>]], dtype=object)
New since 0.10.0, the by keyword can be specified to plot grouped histograms:
In [1488]: data = Series(np.random.randn(1000))
In [1489]: data.hist(by=np.random.randint(0, 4, 1000))
Out[1489]:
array([[<matplotlib.axes.AxesSubplot object at 0xf61ac0c>,
<matplotlib.axes.AxesSubplot object at 0x105b8dac>],
[<matplotlib.axes.AxesSubplot object at 0x1067760c>,
<matplotlib.axes.AxesSubplot object at 0x106eeaec>]], dtype=object)
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 [1490]: df = DataFrame(np.random.rand(10,5))
In [1491]: plt.figure();
In [1491]: bp = df.boxplot()
You can create a stratified boxplot using the by keyword argument to create groupings. For instance,
In [1492]: df = DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
In [1493]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
In [1494]: plt.figure();
In [1494]: bp = df.boxplot(by='X')
You can also pass a subset of columns to plot, as well as group by multiple columns:
In [1495]: df = DataFrame(np.random.rand(10,3), columns=['Col1', 'Col2', 'Col3'])
In [1496]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
In [1497]: df['Y'] = Series(['A','B','A','B','A','B','A','B','A','B'])
In [1498]: plt.figure();
In [1498]: bp = df.boxplot(column=['Col1','Col2'], by=['X','Y'])
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 [1499]: from pandas.tools.plotting import scatter_matrix
In [1500]: df = DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
In [1501]: scatter_matrix(df, alpha=0.2, figsize=(8, 8), diagonal='kde')
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1501-b2cb364f7f2b> in <module>()
----> 1 scatter_matrix(df, alpha=0.2, figsize=(8, 8), diagonal='kde')
/usr/src/tmp/python-module-pandas-buildroot/usr/lib/python2.7/site-packages/pandas/tools/plotting.pyc in scatter_matrix(frame, alpha, figsize, ax, grid, diagonal, marker, **kwds)
141 ax.hist(values)
142 elif diagonal in ('kde', 'density'):
--> 143 from scipy.stats import gaussian_kde
144 y = values
145 gkde = gaussian_kde(y)
ImportError: No module named scipy.stats
New in 0.8.0 You can create density plots using the Series/DataFrame.plot and setting kind=’kde’:
In [1502]: ser = Series(np.random.randn(1000))
In [1503]: ser.plot(kind='kde')
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1503-ae1c951bf9d1> in <module>()
----> 1 ser.plot(kind='kde')
/usr/src/tmp/python-module-pandas-buildroot/usr/lib/python2.7/site-packages/pandas/tools/plotting.pyc in plot_series(series, label, kind, use_index, rot, xticks, yticks, xlim, ylim, ax, style, grid, legend, logx, logy, secondary_y, **kwds)
1532 secondary_y=secondary_y, **kwds)
1533
-> 1534 plot_obj.generate()
1535 plot_obj.draw()
1536
/usr/src/tmp/python-module-pandas-buildroot/usr/lib/python2.7/site-packages/pandas/tools/plotting.pyc in generate(self)
733 self._compute_plot_data()
734 self._setup_subplots()
--> 735 self._make_plot()
736 self._post_plot_logic()
737 self._adorn_subplots()
/usr/src/tmp/python-module-pandas-buildroot/usr/lib/python2.7/site-packages/pandas/tools/plotting.pyc in _make_plot(self)
970
971 def _make_plot(self):
--> 972 from scipy.stats import gaussian_kde
973 plotf = self._get_plot_function()
974 for i, (label, y) in enumerate(self._iter_data()):
ImportError: No module named scipy.stats
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 [1504]: from pandas import read_csv
In [1505]: from pandas.tools.plotting import andrews_curves
In [1506]: data = read_csv('data/iris.data')
In [1507]: plt.figure()
Out[1507]: <matplotlib.figure.Figure at 0x11a735ec>
In [1508]: andrews_curves(data, 'Name')
Out[1508]: <matplotlib.axes.AxesSubplot at 0x119ed5ac>
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 [1509]: from pandas import read_csv
In [1510]: from pandas.tools.plotting import parallel_coordinates
In [1511]: data = read_csv('data/iris.data')
In [1512]: plt.figure()
Out[1512]: <matplotlib.figure.Figure at 0x121fecec>
In [1513]: parallel_coordinates(data, 'Name')
Out[1513]: <matplotlib.axes.AxesSubplot at 0x122000ec>
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 [1514]: from pandas.tools.plotting import lag_plot
In [1515]: plt.figure()
Out[1515]: <matplotlib.figure.Figure at 0x1252b18c>
In [1516]: data = Series(0.1 * np.random.random(1000) +
......: 0.9 * np.sin(np.linspace(-99 * np.pi, 99 * np.pi, num=1000)))
......:
In [1517]: lag_plot(data)
Out[1517]: <matplotlib.axes.AxesSubplot at 0x1252b7ac>
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 [1518]: from pandas.tools.plotting import autocorrelation_plot
In [1519]: plt.figure()
Out[1519]: <matplotlib.figure.Figure at 0x125d85cc>
In [1520]: data = Series(0.7 * np.random.random(1000) +
......: 0.3 * np.sin(np.linspace(-9 * np.pi, 9 * np.pi, num=1000)))
......:
In [1521]: autocorrelation_plot(data)
Out[1521]: <matplotlib.axes.AxesSubplot at 0x125276cc>
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 [1522]: from pandas.tools.plotting import bootstrap_plot
In [1523]: data = Series(np.random.random(1000))
In [1524]: bootstrap_plot(data, size=50, samples=500, color='grey')
Out[1524]: <matplotlib.figure.Figure at 0x1272cbec>
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 [1525]: from pandas import read_csv
In [1526]: from pandas.tools.plotting import radviz
In [1527]: data = read_csv('data/iris.data')
In [1528]: plt.figure()
Out[1528]: <matplotlib.figure.Figure at 0x12c0916c>
In [1529]: radviz(data, 'Name')
Out[1529]: <matplotlib.axes.AxesSubplot at 0x12c095ac>