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 [1]: 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 [2]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
In [3]: ts = ts.cumsum()
In [4]: ts.plot()
Out[4]: <matplotlib.axes.AxesSubplot at 0x5dfb2d0>
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 [5]: plt.figure(); ts.plot(style='k--', label='Series'); plt.legend()
Out[5]: <matplotlib.legend.Legend at 0xfda3210>
On DataFrame, plot is a convenience to plot all of the columns with labels:
In [6]: df = DataFrame(randn(1000, 4), index=ts.index, columns=list('ABCD'))
In [7]: df = df.cumsum()
In [8]: plt.figure(); df.plot(); plt.legend(loc='best')
Out[8]: <matplotlib.legend.Legend at 0x12f2b590>
You may set the legend argument to False to hide the legend, which is shown by default.
In [9]: df.plot(legend=False)
Out[9]: <matplotlib.axes.AxesSubplot at 0x97aa3d0>
Some other options are available, like plotting each Series on a different axis:
In [10]: df.plot(subplots=True, figsize=(6, 6)); plt.legend(loc='best')
Out[10]: <matplotlib.legend.Legend at 0x13024d50>
You may pass logy to get a log-scale Y axis.
In [11]: plt.figure();
In [12]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
In [13]: ts = np.exp(ts.cumsum())
In [14]: ts.plot(logy=True)
Out[14]: <matplotlib.axes.AxesSubplot at 0x12fe8490>
You can plot one column versus another using the x and y keywords in DataFrame.plot:
In [15]: plt.figure()
Out[15]: <matplotlib.figure.Figure at 0x144bf810>
In [16]: df3 = DataFrame(randn(1000, 2), columns=['B', 'C']).cumsum()
In [17]: df3['A'] = Series(list(range(len(df))))
In [18]: df3.plot(x='A', y='B')
Out[18]: <matplotlib.axes.AxesSubplot at 0x14f20e50>
Plotting on a Secondary Y-axis¶
To plot data on a secondary y-axis, use the secondary_y keyword:
In [19]: plt.figure()
Out[19]: <matplotlib.figure.Figure at 0x144f2450>
In [20]: df.A.plot()
Out[20]: <matplotlib.axes.AxesSubplot at 0x14f20d90>
In [21]: df.B.plot(secondary_y=True, style='g')
Out[21]: <matplotlib.axes.AxesSubplot at 0x98edf90>
Selective Plotting on Secondary Y-axis¶
To plot some columns in a DataFrame, give the column names to the secondary_y keyword:
In [22]: plt.figure()
Out[22]: <matplotlib.figure.Figure at 0x144caa10>
In [23]: ax = df.plot(secondary_y=['A', 'B'])
In [24]: ax.set_ylabel('CD scale')
Out[24]: <matplotlib.text.Text at 0x148c4910>
In [25]: ax.right_ax.set_ylabel('AB scale')
Out[25]: <matplotlib.text.Text at 0x151ac950>
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 [26]: plt.figure()
Out[26]: <matplotlib.figure.Figure at 0x151b3050>
In [27]: df.plot(secondary_y=['A', 'B'], mark_right=False)
Out[27]: <matplotlib.axes.AxesSubplot at 0x148f0290>
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 [28]: plt.figure()
Out[28]: <matplotlib.figure.Figure at 0x13057ad0>
In [29]: df.A.plot()
Out[29]: <matplotlib.axes.AxesSubplot at 0x130572d0>
Using the x_compat parameter, you can suppress this behavior:
In [30]: plt.figure()
Out[30]: <matplotlib.figure.Figure at 0x13057d50>
In [31]: df.A.plot(x_compat=True)
Out[31]: <matplotlib.axes.AxesSubplot at 0x73208d0>
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 [32]: import pandas as pd
In [33]: plt.figure()
Out[33]: <matplotlib.figure.Figure at 0x12f7fad0>
In [34]: 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 [35]: fig, axes = plt.subplots(nrows=2, ncols=2)
In [36]: df['A'].plot(ax=axes[0,0]); axes[0,0].set_title('A')
Out[36]: <matplotlib.text.Text at 0x148f5c90>
In [37]: df['B'].plot(ax=axes[0,1]); axes[0,1].set_title('B')
Out[37]: <matplotlib.text.Text at 0x98ec550>
In [38]: df['C'].plot(ax=axes[1,0]); axes[1,0].set_title('C')
Out[38]: <matplotlib.text.Text at 0x146b6e90>
In [39]: df['D'].plot(ax=axes[1,1]); axes[1,1].set_title('D')
Out[39]: <matplotlib.text.Text at 0x146cb690>
Other plotting features¶
Bar plots¶
For labeled, non-time series data, you may wish to produce a bar plot:
In [40]: plt.figure();
In [41]: df.ix[5].plot(kind='bar'); plt.axhline(0, color='k')
Out[41]: <matplotlib.lines.Line2D at 0x97c8b50>
Calling a DataFrame’s plot method with kind='bar' produces a multiple bar plot:
In [42]: df2 = DataFrame(rand(10, 4), columns=['a', 'b', 'c', 'd'])
In [43]: df2.plot(kind='bar');
To produce a stacked bar plot, pass stacked=True:
In [44]: df2.plot(kind='bar', stacked=True);
To get horizontal bar plots, pass kind='barh':
In [45]: df2.plot(kind='barh', stacked=True);
Histograms¶
In [46]: plt.figure();
In [47]: df['A'].diff().hist()
Out[47]: <matplotlib.axes.AxesSubplot at 0x16376b10>
For a DataFrame, hist plots the histograms of the columns on multiple subplots:
In [48]: plt.figure()
Out[48]: <matplotlib.figure.Figure at 0x16afefd0>
In [49]: df.diff().hist(color='k', alpha=0.5, bins=50)
Out[49]:
array([[<matplotlib.axes.AxesSubplot object at 0x16af1ed0>,
<matplotlib.axes.AxesSubplot object at 0x169a6a50>],
[<matplotlib.axes.AxesSubplot object at 0x16c37750>,
<matplotlib.axes.AxesSubplot object at 0x16c4a250>]], dtype=object)
New since 0.10.0, the by keyword can be specified to plot grouped histograms:
In [50]: data = Series(randn(1000))
In [51]: data.hist(by=randint(0, 4, 1000), figsize=(6, 4))
Out[51]:
array([[<matplotlib.axes.AxesSubplot object at 0x171c73d0>,
<matplotlib.axes.AxesSubplot object at 0x179df8d0>],
[<matplotlib.axes.AxesSubplot object at 0x179fac10>,
<matplotlib.axes.AxesSubplot object at 0x17b1f610>]], 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 [52]: df = DataFrame(rand(10,5))
In [53]: plt.figure();
In [54]: bp = df.boxplot()
You can create a stratified boxplot using the by keyword argument to create groupings. For instance,
In [55]: df = DataFrame(rand(10,2), columns=['Col1', 'Col2'] )
In [56]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
In [57]: plt.figure();
In [58]: bp = df.boxplot(by='X')
You can also pass a subset of columns to plot, as well as group by multiple columns:
In [59]: df = DataFrame(rand(10,3), columns=['Col1', 'Col2', 'Col3'])
In [60]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
In [61]: df['Y'] = Series(['A','B','A','B','A','B','A','B','A','B'])
In [62]: plt.figure();
In [63]: 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 [64]: from pandas.tools.plotting import scatter_matrix
In [65]: df = DataFrame(randn(1000, 4), columns=['a', 'b', 'c', 'd'])
In [66]: scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
Out[66]:
array([[<matplotlib.axes.AxesSubplot object at 0x169ae4d0>,
<matplotlib.axes.AxesSubplot object at 0x17df0350>,
<matplotlib.axes.AxesSubplot object at 0x17e07f90>,
<matplotlib.axes.AxesSubplot object at 0x1818d2d0>],
[<matplotlib.axes.AxesSubplot object at 0x17f70e90>,
<matplotlib.axes.AxesSubplot object at 0x1699b410>,
<matplotlib.axes.AxesSubplot object at 0x1302a790>,
<matplotlib.axes.AxesSubplot object at 0x15cb42d0>],
[<matplotlib.axes.AxesSubplot object at 0x1637d190>,
<matplotlib.axes.AxesSubplot object at 0x98e3490>,
<matplotlib.axes.AxesSubplot object at 0x144d5b50>,
<matplotlib.axes.AxesSubplot object at 0x17b33650>],
[<matplotlib.axes.AxesSubplot object at 0x1816ef90>,
<matplotlib.axes.AxesSubplot object at 0x16376590>,
<matplotlib.axes.AxesSubplot object at 0x144eec10>,
<matplotlib.axes.AxesSubplot object at 0x18421790>]], dtype=object)
New in 0.8.0 You can create density plots using the Series/DataFrame.plot and setting kind=’kde’:
In [67]: ser = Series(randn(1000))
In [68]: ser.plot(kind='kde')
Out[68]: <matplotlib.axes.AxesSubplot at 0x18a9ee90>
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 [69]: from pandas import read_csv
In [70]: from pandas.tools.plotting import andrews_curves
In [71]: data = read_csv('data/iris.data')
In [72]: plt.figure()
Out[72]: <matplotlib.figure.Figure at 0x18ff5390>
In [73]: andrews_curves(data, 'Name')
Out[73]: <matplotlib.axes.AxesSubplot at 0x18ff5710>
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 [74]: from pandas import read_csv
In [75]: from pandas.tools.plotting import parallel_coordinates
In [76]: data = read_csv('data/iris.data')
In [77]: plt.figure()
Out[77]: <matplotlib.figure.Figure at 0x19722450>
In [78]: parallel_coordinates(data, 'Name')
Out[78]: <matplotlib.axes.AxesSubplot at 0x19722550>
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 [79]: from pandas.tools.plotting import lag_plot
In [80]: plt.figure()
Out[80]: <matplotlib.figure.Figure at 0x19db5790>
In [81]: data = Series(0.1 * rand(1000) +
....: 0.9 * np.sin(np.linspace(-99 * np.pi, 99 * np.pi, num=1000)))
....:
In [82]: lag_plot(data)
Out[82]: <matplotlib.axes.AxesSubplot at 0x19d857d0>
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 [83]: from pandas.tools.plotting import autocorrelation_plot
In [84]: plt.figure()
Out[84]: <matplotlib.figure.Figure at 0x19d9ddd0>
In [85]: data = Series(0.7 * rand(1000) +
....: 0.3 * np.sin(np.linspace(-9 * np.pi, 9 * np.pi, num=1000)))
....:
In [86]: autocorrelation_plot(data)
Out[86]: <matplotlib.axes.AxesSubplot at 0x19d9dd90>
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 [87]: from pandas.tools.plotting import bootstrap_plot
In [88]: data = Series(rand(1000))
In [89]: bootstrap_plot(data, size=50, samples=500, color='grey')
Out[89]: <matplotlib.figure.Figure at 0x199eb910>
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 [90]: from pandas import read_csv
In [91]: from pandas.tools.plotting import radviz
In [92]: data = read_csv('data/iris.data')
In [93]: plt.figure()
Out[93]: <matplotlib.figure.Figure at 0x1957b450>
In [94]: radviz(data, 'Name')
Out[94]: <matplotlib.axes.AxesSubplot at 0x1956f3d0>
Colormaps¶
A potential issue when plotting a large number of columns is that it can be difficult to distinguish some series due to repetition in the default colors. To remedy this, DataFrame plotting supports the use of the colormap= argument, which accepts either a Matplotlib colormap or a string that is a name of a colormap registered with Matplotlib. A visualization of the default matplotlib colormaps is available here.
As matplotlib does not directly support colormaps for line-based plots, the colors are selected based on an even spacing determined by the number of columns in the DataFrame. There is no consideration made for background color, so some colormaps will produce lines that are not easily visible.
To use the jet colormap, we can simply pass 'jet' to colormap=
In [95]: df = DataFrame(randn(1000, 10), index=ts.index)
In [96]: df = df.cumsum()
In [97]: plt.figure()
Out[97]: <matplotlib.figure.Figure at 0x1a64b990>
In [98]: df.plot(colormap='jet')
Out[98]: <matplotlib.axes.AxesSubplot at 0x19709a10>
or we can pass the colormap itself
In [99]: from matplotlib import cm
In [100]: plt.figure()
Out[100]: <matplotlib.figure.Figure at 0x179ec350>
In [101]: df.plot(colormap=cm.jet)
Out[101]: <matplotlib.axes.AxesSubplot at 0x19722b90>
Colormaps can also be used other plot types, like bar charts:
In [102]: dd = DataFrame(randn(10, 10)).applymap(abs)
In [103]: dd = dd.cumsum()
In [104]: plt.figure()
Out[104]: <matplotlib.figure.Figure at 0x15cba590>
In [105]: dd.plot(kind='bar', colormap='Greens')
Out[105]: <matplotlib.axes.AxesSubplot at 0x15cc6d50>
Parallel coordinates charts:
In [106]: plt.figure()
Out[106]: <matplotlib.figure.Figure at 0x19c09a50>
In [107]: parallel_coordinates(data, 'Name', colormap='gist_rainbow')
Out[107]: <matplotlib.axes.AxesSubplot at 0x19826410>
Andrews curves charts:
In [108]: plt.figure()
Out[108]: <matplotlib.figure.Figure at 0x192f4310>
In [109]: andrews_curves(data, 'Name', colormap='winter')
Out[109]: <matplotlib.axes.AxesSubplot at 0x19006290>