On this page
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 0x7ff26d422750>
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();
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 0x7ff2667845d0>
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:
- ‘bar’ or ‘barh’ for bar plots
- ‘hist’ for histogram
- ‘box’ for boxplot
- ‘kde’ or
'density'for density plots - ‘area’ for area plots
- ‘scatter’ for scatter plots
- ‘hexbin’ for hexagonal bin plots
- ‘pie’ for pie plots
For example, a bar plot can be created the following way:
In [11]: plt.figure();
In [12]: df.ix[5].plot(kind='bar'); plt.axhline(0, color='k')
Out[12]: <matplotlib.lines.Line2D at 0x7ff266b33890>
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.tools.plotting that take a Series or DataFrame as an argument. These include
- Scatter Matrix
- Andrews Curves
- Parallel Coordinates
- Lag Plot
- Autocorrelation Plot
- Bootstrap Plot
- RadViz
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.ix[5].plot.bar(); plt.axhline(0, color='k')
Out[16]: <matplotlib.lines.Line2D at 0x7ff2673d3510>
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();
To produce a stacked bar plot, pass stacked=True:
In [19]: df2.plot.bar(stacked=True);
To get horizontal bar plots, use the barh method:
In [20]: df2.plot.barh(stacked=True);
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 0x7ff26779c3d0>
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 0x7ff26caf76d0>
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 0x7ff26c2c89d0>
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 0x7ff2770919d0>
DataFrame.hist() plots the histograms of the columns on multiple subplots:
In [30]: plt.figure()
Out[30]: <matplotlib.figure.Figure at 0x7ff26d67c090>
In [31]: df.diff().hist(color='k', alpha=0.5, bins=50)
Out[31]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff2726264d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff2667c8390>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff266667a50>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff2671545d0>]], dtype=object)
New in version 0.10.0.
The by keyword can be specified to plot grouped histograms:
In [32]: data = pd.Series(np.random.randn(1000))
In [33]: data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4))
Out[33]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff266750690>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26c71e110>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26735f750>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26c2fe650>]], dtype=object)
Box Plots
New in version 0.15.0.
Boxplot can be drawn calling Series.plot.box() and DataFrame.plot.box(), or DataFrame.boxplot() 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 [34]: df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
In [35]: df.plot.box()
Out[35]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff27132a050>
Boxplot can be colorized by passing color keyword. You can pass a dict whose keys are boxes, whiskers, medians and caps. If some keys are missing in the dict, default colors are used for the corresponding artists. Also, boxplot has sym keyword to specify fliers style.
When you pass other type of arguments via color keyword, it will be directly passed to matplotlib for all the boxes, whiskers, medians and caps colorization.
The colors are applied to every boxes to be drawn. If you want more complicated colorization, you can get each drawn artists by passing return_type.
In [36]: color = dict(boxes='DarkGreen', whiskers='DarkOrange',
....: medians='DarkBlue', caps='Gray')
....:
In [37]: df.plot.box(color=color, sym='r+')
Out[37]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff26c76b890>
Also, you can pass other keywords supported by matplotlib boxplot. For example, horizontal and custom-positioned boxplot can be drawn by vert=False and positions keywords.
In [38]: df.plot.box(vert=False, positions=[1, 4, 5, 6, 8])
Out[38]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff26c1f2dd0>
See the boxplot method and the matplotlib boxplot documentation for more.
The existing interface DataFrame.boxplot to plot boxplot still can be used.
In [39]: df = pd.DataFrame(np.random.rand(10,5))
In [40]: plt.figure();
In [41]: bp = df.boxplot()
You can create a stratified boxplot using the by keyword argument to create groupings. For instance,
In [42]: df = pd.DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
In [43]: df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])
In [44]: plt.figure();
In [45]: bp = df.boxplot(by='X')
You can also pass a subset of columns to plot, as well as group by multiple columns:
In [46]: df = pd.DataFrame(np.random.rand(10,3), columns=['Col1', 'Col2', 'Col3'])
In [47]: df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])
In [48]: df['Y'] = pd.Series(['A','B','A','B','A','B','A','B','A','B'])
In [49]: plt.figure();
In [50]: bp = df.boxplot(column=['Col1','Col2'], by=['X','Y'])
Warning
The default changed from 'dict' to 'axes' in version 0.19.0.
In boxplot, the return type can be controlled by the return_type, keyword. The valid choices are {"axes", "dict", "both", None}. Faceting, created by DataFrame.boxplot with the by keyword, will affect the output type as well:
return_type= |
Faceted | Output type |
None |
No | axes |
None |
Yes | 2-D ndarray of axes |
'axes' |
No | axes |
'axes' |
Yes | Series of axes |
'dict' |
No | dict of artists |
'dict' |
Yes | Series of dicts of artists |
'both' |
No | namedtuple |
'both' |
Yes | Series of namedtuples |
Groupby.boxplot always returns a Series of return_type.
In [51]: np.random.seed(1234)
In [52]: df_box = pd.DataFrame(np.random.randn(50, 2))
In [53]: df_box['g'] = np.random.choice(['A', 'B'], size=50)
In [54]: df_box.loc[df_box['g'] == 'B', 1] += 3
In [55]: bp = df_box.boxplot(by='g')
Compare to:
In [56]: bp = df_box.groupby('g').boxplot()
Area Plot
New in version 0.14.
You can create area plots with Series.plot.area() and DataFrame.plot.area(). Area plots are stacked by default. To produce stacked area plot, each column must be either all positive or all negative values.
When input data contains NaN, it will be automatically filled by 0. If you want to drop or fill by different values, use dataframe.dropna() or dataframe.fillna() before calling plot.
In [57]: df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
In [58]: df.plot.area();
To produce an unstacked plot, pass stacked=False. Alpha value is set to 0.5 unless otherwise specified:
In [59]: df.plot.area(stacked=False);
Scatter Plot
New in version 0.13.
Scatter plot can be drawn by using the DataFrame.plot.scatter() method. Scatter plot requires numeric columns for x and y axis. These can be specified by x and y keywords each.
In [60]: df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])
In [61]: df.plot.scatter(x='a', y='b');
To plot multiple column groups in a single axes, repeat plot method specifying target ax. It is recommended to specify color and label keywords to distinguish each groups.
In [62]: ax = df.plot.scatter(x='a', y='b', color='DarkBlue', label='Group 1');
In [63]: df.plot.scatter(x='c', y='d', color='DarkGreen', label='Group 2', ax=ax);
The keyword c may be given as the name of a column to provide colors for each point:
In [64]: df.plot.scatter(x='a', y='b', c='c', s=50);
You can pass other keywords supported by matplotlib scatter. Below example shows a bubble chart using a dataframe column values as bubble size.
In [65]: df.plot.scatter(x='a', y='b', s=df['c']*200);
See the scatter method and the matplotlib scatter documentation for more.
Hexagonal Bin Plot
New in version 0.14.
You can create hexagonal bin plots with DataFrame.plot.hexbin(). Hexbin plots can be a useful alternative to scatter plots if your data are too dense to plot each point individually.
In [66]: df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
In [67]: df['b'] = df['b'] + np.arange(1000)
In [68]: df.plot.hexbin(x='a', y='b', gridsize=25)
Out[68]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff2713ce350>
A useful keyword argument is gridsize; it controls the number of hexagons in the x-direction, and defaults to 100. A larger gridsize means more, smaller bins.
By default, a histogram of the counts around each (x, y) point is computed. You can specify alternative aggregations by passing values to the C and reduce_C_function arguments. C specifies the value at each (x, y) point and reduce_C_function is a function of one argument that reduces all the values in a bin to a single number (e.g. mean, max, sum, std). In this example the positions are given by columns a and b, while the value is given by column z. The bins are aggregated with numpy’s max function.
In [69]: df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
In [70]: df['b'] = df['b'] = df['b'] + np.arange(1000)
In [71]: df['z'] = np.random.uniform(0, 3, 1000)
In [72]: df.plot.hexbin(x='a', y='b', C='z', reduce_C_function=np.max,
....: gridsize=25)
....:
Out[72]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff2669b58d0>
See the hexbin method and the matplotlib hexbin documentation for more.
Pie plot
New in version 0.14.
You can create a pie plot with DataFrame.plot.pie() or Series.plot.pie(). If your data includes any NaN, they will be automatically filled with 0. A ValueError will be raised if there are any negative values in your data.
In [73]: series = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
In [74]: series.plot.pie(figsize=(6, 6))
Out[74]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff26c8ac210>
For pie plots it’s best to use square figures, one’s with an equal aspect ratio. You can create the figure with equal width and height, or force the aspect ratio to be equal after plotting by calling ax.set_aspect('equal') on the returned axes object.
Note that pie plot with DataFrame requires that you either specify a target column by the y argument or subplots=True. When y is specified, pie plot of selected column will be drawn. If subplots=True is specified, pie plots for each column are drawn as subplots. A legend will be drawn in each pie plots by default; specify legend=False to hide it.
In [75]: df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])
In [76]: df.plot.pie(subplots=True, figsize=(8, 4))
Out[76]:
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26c896f50>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26ceb2750>], dtype=object)
You can use the labels and colors keywords to specify the labels and colors of each wedge.
Warning
Most pandas plots use the the label and color arguments (note the lack of “s” on those). To be consistent with matplotlib.pyplot.pie() you must use labels and colors.
If you want to hide wedge labels, specify labels=None. If fontsize is specified, the value will be applied to wedge labels. Also, other keywords supported by matplotlib.pyplot.pie() can be used.
In [77]: series.plot.pie(labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'],
....: autopct='%.2f', fontsize=20, figsize=(6, 6))
....:
Out[77]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff270fede50>
If you pass values whose sum total is less than 1.0, matplotlib draws a semicircle.
In [78]: series = pd.Series([0.1] * 4, index=['a', 'b', 'c', 'd'], name='series2')
In [79]: series.plot.pie(figsize=(6, 6))
Out[79]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff26c39e9d0>
See the matplotlib pie documentation for more.
Plotting with Missing Data
Pandas tries to be pragmatic about plotting DataFrames or Series that contain missing data. Missing values are dropped, left out, or filled depending on the plot type.
| Plot Type | NaN Handling |
|---|---|
| Line | Leave gaps at NaNs |
| Line (stacked) | Fill 0’s |
| Bar | Fill 0’s |
| Scatter | Drop NaNs |
| Histogram | Drop NaNs (column-wise) |
| Box | Drop NaNs (column-wise) |
| Area | Fill 0’s |
| KDE | Drop NaNs (column-wise) |
| Hexbin | Drop NaNs |
| Pie | Fill 0’s |
If any of these defaults are not what you want, or if you want to be explicit about how missing values are handled, consider using fillna() or dropna() before plotting.
Plotting Tools
These functions can be imported from pandas.tools.plotting and take a Series or DataFrame as an argument.
Scatter Matrix Plot
New in version 0.7.3.
You can create a scatter plot matrix using the scatter_matrix method in pandas.tools.plotting:
In [80]: from pandas.tools.plotting import scatter_matrix
In [81]: df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
In [82]: scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
Out[82]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26def9410>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff2705099d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26cff4050>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26e422990>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26e1ffe10>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26d005250>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff2701eb2d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26d058090>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff267867110>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff2679232d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff271ddb290>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26ee92210>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26ddd2350>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26e2142d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26df3d0d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7ff26d59c2d0>]], dtype=object)
Density Plot
New in version 0.8.0.
You can create density plots using the Series.plot.kde() and DataFrame.plot.kde() methods.
In [83]: ser = pd.Series(np.random.randn(1000))
In [84]: ser.plot.kde()
Out[84]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff266c28d10>
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 [85]: from pandas.tools.plotting import andrews_curves
In [86]: data = pd.read_csv('data/iris.data')
In [87]: plt.figure()
Out[87]: <matplotlib.figure.Figure at 0x7ff26c276bd0>
In [88]: andrews_curves(data, 'Name')
Out[88]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff270a8a9d0>
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 [89]: from pandas.tools.plotting import parallel_coordinates
In [90]: data = pd.read_csv('data/iris.data')
In [91]: plt.figure()
Out[91]: <matplotlib.figure.Figure at 0x7ff26798f850>
In [92]: parallel_coordinates(data, 'Name')
Out[92]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff267994810>