Plotting

We use the standard convention for referencing the matplotlib API:

In [1]: import matplotlib.pyplot as plt

New in version 0.11.0.

The plots in this document are made using matplotlib’s ggplot style (new in version 1.4). If your version of matplotlib is 1.3 or lower, setting the display.mpl_style to 'default' with pd.options.display.mpl_style = 'default' to produce more appealing plots. When set, matplotlib’s rcParams are changed (globally!) to nicer-looking settings.

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 = Series(randn(1000), index=date_range('1/1/2000', periods=1000))

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

In [4]: ts.plot()
Out[4]: <matplotlib.axes._subplots.AxesSubplot at 0xaf5331ac>
_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 = DataFrame(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 = DataFrame(randn(1000, 2), columns=['B', 'C']).cumsum()

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

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

Note

For more formatting and sytling options, see below.

Other Plots

The kind keyword argument of plot() accepts a handful of values for plots other than the default Line plot. These include:

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

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 [11]: plt.figure();

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

Calling a DataFrame’s plot() method with kind='bar' produces a multiple bar plot:

In [13]: df2 = DataFrame(rand(10, 4), columns=['a', 'b', 'c', 'd'])

In [14]: df2.plot(kind='bar');
_images/bar_plot_multi_ex.png

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

In [15]: df2.plot(kind='bar', stacked=True);
_images/bar_plot_stacked_ex.png

To get horizontal bar plots, pass kind='barh':

In [16]: df2.plot(kind='barh', stacked=True);
_images/barh_plot_stacked_ex.png

Histograms

New in version 0.15.0.

Histogram can be drawn specifying kind='hist'.

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

In [18]: plt.figure();

In [19]: df4.plot(kind='hist', alpha=0.5)
Out[19]: <matplotlib.axes._subplots.AxesSubplot at 0xaef60c4c>
_images/hist_new.png

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

In [20]: plt.figure();

In [21]: df4.plot(kind='hist', stacked=True, bins=20)
Out[21]: <matplotlib.axes._subplots.AxesSubplot at 0xaef5286c>
_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 [22]: plt.figure();

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

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

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

In [24]: plt.figure();

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

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

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

In [27]: df.diff().hist(color='k', alpha=0.5, bins=50)
Out[27]: 
array([[<matplotlib.axes._subplots.AxesSubplot object at 0xaf2ad58c>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xaf057cec>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0xaea64dec>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xaea1a50c>]], dtype=object)
_images/frame_hist_ex.png

New in version 0.10.0.

The by keyword can be specified to plot grouped histograms:

In [28]: data = Series(randn(1000))

In [29]: data.hist(by=randint(0, 4, 1000), figsize=(6, 4))
Out[29]: 
array([[<matplotlib.axes._subplots.AxesSubplot object at 0xae462eac>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xae5adf6c>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0xae56cfac>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xae52034c>]], dtype=object)
_images/grouped_hist.png

Box Plots

Boxplot can be drawn calling a Series and DataFrame.plot with kind='box', or DataFrame.boxplot to visualize the distribution of values within each column.

New in version 0.15.0.

plot method now supports kind='box' to draw boxplot.

For instance, here is a boxplot representing five trials of 10 observations of a uniform random variable on [0,1).

In [30]: df = DataFrame(rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])

In [31]: df.plot(kind='box')
Out[31]: <matplotlib.axes._subplots.AxesSubplot at 0xaef67a6c>
_images/box_plot_new.png

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 [32]: color = dict(boxes='DarkGreen', whiskers='DarkOrange',
   ....:              medians='DarkBlue', caps='Gray')
   ....: 

In [33]: df.plot(kind='box', color=color, sym='r+')
Out[33]: <matplotlib.axes._subplots.AxesSubplot at 0xadc9014c>
_images/box_new_colorize.png

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 [34]: df.plot(kind='box', vert=False, positions=[1, 4, 5, 6, 8])
Out[34]: <matplotlib.axes._subplots.AxesSubplot at 0xadb33e8c>
_images/box_new_kwargs.png

See the boxplot method and the matplotlib boxplot documenation for more.

The existing interface DataFrame.boxplot to plot boxplot still can be used.

In [35]: df = DataFrame(rand(10,5))

In [36]: plt.figure();

In [37]: bp = df.boxplot()
_images/box_plot_ex.png

You can create a stratified boxplot using the by keyword argument to create groupings. For instance,

In [38]: df = DataFrame(rand(10,2), columns=['Col1', 'Col2'] )

In [39]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])

In [40]: plt.figure();

In [41]: bp = df.boxplot(by='X')
_images/box_plot_ex2.png

You can also pass a subset of columns to plot, as well as group by multiple columns:

In [42]: df = DataFrame(rand(10,3), columns=['Col1', 'Col2', 'Col3'])

In [43]: df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])

In [44]: df['Y'] = Series(['A','B','A','B','A','B','A','B','A','B'])

In [45]: plt.figure();

In [46]: bp = df.boxplot(column=['Col1','Col2'], by=['X','Y'])
_images/box_plot_ex3.png

Basically, plot functions return matplotlib Axes as a return value. In boxplot, the return type can be changed by argument return_type, and whether the subplots is enabled (subplots=True in plot or by is specified in boxplot).

When subplots=False / by is None:

  • if return_type is 'dict', a dictionary containing the matplotlib Lines is returned. The keys are “boxes”, “caps”, “fliers”, “medians”, and “whiskers”.

    This is the default of boxplot in historical reason. Note that plot(kind='box') returns Axes as default as the same as other plots.

  • if return_type is 'axes', a matplotlib Axes containing the boxplot is returned.

  • if return_type is 'both' a namedtuple containging the matplotlib Axes

    and matplotlib Lines is returned

When subplots=True / by is some column of the DataFrame:

  • A dict of return_type is returned, where the keys are the columns of the DataFrame. The plot has a facet for each column of the DataFrame, with a separate box for each value of by.

Finally, when calling boxplot on a Groupby object, a dict of return_type is returned, where the keys are the same as the Groupby object. The plot has a facet for each key, with each facet containing a box for each column of the DataFrame.

In [47]: np.random.seed(1234)

In [48]: df_box = DataFrame(np.random.randn(50, 2))

In [49]: df_box['g'] = np.random.choice(['A', 'B'], size=50)

In [50]: df_box.loc[df_box['g'] == 'B', 1] += 3

In [51]: bp = df_box.boxplot(by='g')
_images/boxplot_groupby.png

Compare to:

In [52]: bp = df_box.groupby('g').boxplot()
_images/groupby_boxplot_vis.png

Area Plot

New in version 0.14.

You can create area plots with Series.plot and DataFrame.plot by passing kind='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 [53]: df = DataFrame(rand(10, 4), columns=['a', 'b', 'c', 'd'])

In [54]: df.plot(kind='area');
_images/area_plot_stacked.png

To produce an unstacked plot, pass stacked=False. Alpha value is set to 0.5 unless otherwise specified:

In [55]: df.plot(kind='area', stacked=False);
_images/area_plot_unstacked.png

Scatter Plot

New in version 0.13.

You can create scatter plots with DataFrame.plot by passing kind='scatter'. Scatter plot requires numeric columns for x and y axis. These can be specified by x and y keywords each.

In [56]: df = DataFrame(rand(50, 4), columns=['a', 'b', 'c', 'd'])

In [57]: df.plot(kind='scatter', x='a', y='b');
_images/scatter_plot.png

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 [58]: ax = df.plot(kind='scatter', x='a', y='b',
   ....:              color='DarkBlue', label='Group 1');
   ....: 

In [59]: df.plot(kind='scatter', x='c', y='d',
   ....:         color='DarkGreen', label='Group 2', ax=ax);
   ....: 
_images/scatter_plot_repeated.png

The keyword c may be given as the name of a column to provide colors for each point:

In [60]: df.plot(kind='scatter', x='a', y='b', c='c', s=50);
_images/scatter_plot_colored.png

You can pass other keywords supported by matplotlib scatter. Below example shows a bubble chart using a dataframe column values as bubble size.

In [61]: df.plot(kind='scatter', x='a', y='b', s=df['c']*200);
_images/scatter_plot_bubble.png

See the scatter method and the matplotlib scatter documenation for more.

Hexagonal Bin Plot

New in version 0.14.

You can create hexagonal bin plots with DataFrame.plot() and kind='hexbin'. Hexbin plots can be a useful alternative to scatter plots if your data are too dense to plot each point individually.

In [62]: df = DataFrame(randn(1000, 2), columns=['a', 'b'])

In [63]: df['b'] = df['b'] + np.arange(1000)

In [64]: df.plot(kind='hexbin', x='a', y='b', gridsize=25)
Out[64]: <matplotlib.axes._subplots.AxesSubplot at 0xacd5c6ac>
_images/hexbin_plot.png

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 [65]: df = DataFrame(randn(1000, 2), columns=['a', 'b'])

In [66]: df['b'] = df['b'] = df['b'] + np.arange(1000)

In [67]: df['z'] = np.random.uniform(0, 3, 1000)

In [68]: df.plot(kind='hexbin', x='a', y='b', C='z', reduce_C_function=np.max,
   ....:         gridsize=25)
   ....: 
Out[68]: <matplotlib.axes._subplots.AxesSubplot at 0xad76dbcc>
_images/hexbin_plot_agg.png

See the hexbin method and the matplotlib hexbin documenation for more.

Pie plot

New in version 0.14.

You can create a pie plot with DataFrame.plot() or Series.plot() with kind='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 [69]: series = Series(3 * rand(4), index=['a', 'b', 'c', 'd'], name='series')

In [70]: series.plot(kind='pie', figsize=(6, 6))
Out[70]: <matplotlib.axes._subplots.AxesSubplot at 0xade76c2c>
_images/series_pie_plot.png

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 [71]: df = DataFrame(3 * rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])

In [72]: df.plot(kind='pie', subplots=True, figsize=(8, 4))
Out[72]: 
array([<matplotlib.axes._subplots.AxesSubplot object at 0xadeaf62c>,
       <matplotlib.axes._subplots.AxesSubplot object at 0xadaa40cc>], dtype=object)
_images/df_pie_plot.png

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 (not 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 [73]: series.plot(kind='pie', labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'],
   ....:             autopct='%.2f', fontsize=20, figsize=(6, 6))
   ....: 
Out[73]: <matplotlib.axes._subplots.AxesSubplot at 0xad7aac6c>
_images/series_pie_plot_options.png

If you pass values whose sum total is less than 1.0, matplotlib draws a semicircle.

In [74]: series = Series([0.1] * 4, index=['a', 'b', 'c', 'd'], name='series2')

In [75]: series.plot(kind='pie', figsize=(6, 6))
Out[75]: <matplotlib.axes._subplots.AxesSubplot at 0xad7b4acc>
_images/series_pie_plot_semi.png

See the matplotlib pie documenation 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 [76]: from pandas.tools.plotting import scatter_matrix

In [77]: df = DataFrame(randn(1000, 4), columns=['a', 'b', 'c', 'd'])

In [78]: scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
Out[78]: 
array([[<matplotlib.axes._subplots.AxesSubplot object at 0xad874f0c>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xad71cbec>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xad8498cc>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xac4a632c>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0xac46652c>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xac492e6c>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xac452d2c>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xac40726c>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0xac3c73cc>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xac0c31ec>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xac07746c>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xac03746c>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0xadf5b2ac>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xad23760c>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xaccaf3cc>,
        <matplotlib.axes._subplots.AxesSubplot object at 0xaccfbb0c>]], dtype=object)
_images/scatter_matrix_kde.png

Density Plot

New in version 0.8.0.

You can create density plots using the Series/DataFrame.plot and setting kind='kde':

In [79]: ser = Series(randn(1000))

In [80]: ser.plot(kind='kde')
Out[80]: <matplotlib.axes._subplots.AxesSubplot at 0xa9a75e2c>
_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 [81]: from pandas import read_csv

In [82]: from pandas.tools.plotting import andrews_curves

In [83]: data = read_csv('data/iris.data')

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

In [85]: andrews_curves(data, 'Name')
Out[85]: <matplotlib.axes._subplots.AxesSubplot at 0xa995852c>
_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 [86]: from pandas import read_csv

In [87]: from pandas.tools.plotting import parallel_coordinates

In [88]: data = read_csv('data/iris.data')

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

In [90]: parallel_coordinates(data, 'Name')
Out[90]: <matplotlib.axes._subplots.AxesSubplot at 0xa98b30cc>
_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 [91]: from pandas.tools.plotting import lag_plot

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

In [93]: data = Series(0.1 * rand(1000) +
   ....:    0.9 * np.sin(np.linspace(-99 * np.pi, 99 * np.pi, num=1000)))
   ....: 

In [94]: lag_plot(data)
Out[94]: <matplotlib.axes._subplots.AxesSubplot at 0xa929414c>
_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 [95]: from pandas.tools.plotting import autocorrelation_plot

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

In [97]: data = Series(0.7 * rand(1000) +
   ....:    0.3 * np.sin(np.linspace(-9 * np.pi, 9 * np.pi, num=1000)))
   ....: 

In [98]: autocorrelation_plot(data)
Out[98]: <matplotlib.axes._subplots.AxesSubplot at 0xa929ad4c>
_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 [99]: from pandas.tools.plotting import bootstrap_plot

In [100]: data = Series(rand(1000))

In [101]: bootstrap_plot(data, size=50, samples=500, color='grey')
Out[101]: <matplotlib.figure.Figure at 0xa905dcec>
_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 [102]: from pandas import read_csv

In [103]: from pandas.tools.plotting import radviz

In [104]: data = read_csv('data/iris.data')

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

In [106]: radviz(data, 'Name')
Out[106]: <matplotlib.axes._subplots.AxesSubplot at 0xa909024c>
_images/radviz.png

Plot Formatting

Most plotting methods have a set of keyword arguments that control the layout and formatting of the returned plot:

In [107]: plt.figure(); ts.plot(style='k--', label='Series');
_images/series_plot_basic2.png

For each kind of plot (e.g. line, bar, scatter) any additional arguments keywords are passed along to the corresponding matplotlib function (ax.plot(), ax.bar(), ax.scatter()). These can be used to control additional styling, beyond what pandas provides.

Controlling the Legend

You may set the legend argument to False to hide the legend, which is shown by default.

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

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

In [110]: df.plot(legend=False)
Out[110]: <matplotlib.axes._subplots.AxesSubplot at 0xa8a0ab6c>
_images/frame_plot_basic_noleg.png

Scales

You may pass logy to get a log-scale Y axis.

In [111]: ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))

In [112]: ts = np.exp(ts.cumsum())

In [113]: ts.plot(logy=True)
Out[113]: <matplotlib.axes._subplots.AxesSubplot at 0xa87f3f6c>
_images/series_plot_logy.png

See also the logx and loglog keyword arguments.

Plotting on a Secondary Y-axis

To plot data on a secondary y-axis, use the secondary_y keyword:

In [114]: df.A.plot()
Out[114]: <matplotlib.axes._subplots.AxesSubplot at 0xa8b269cc>

In [115]: df.B.plot(secondary_y=True, style='g')
Out[115]: <matplotlib.axes._subplots.AxesSubplot at 0xa82b10cc>
_images/series_plot_secondary_y.png

To plot some columns in a DataFrame, give the column names to the secondary_y keyword:

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

In [117]: ax = df.plot(secondary_y=['A', 'B'])

In [118]: ax.set_ylabel('CD scale')
Out[118]: <matplotlib.text.Text at 0xa81eb84c>

In [119]: ax.right_ax.set_ylabel('AB scale')
Out[119]: <matplotlib.text.Text at 0xa81ad9ac>
_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 [120]: plt.figure()
Out[120]: <matplotlib.figure.Figure at 0xa86c4e0c>

In [121]: df.plot(secondary_y=['A', 'B'], mark_right=False)
Out[121]: <matplotlib.axes._subplots.AxesSubplot at 0xa7e5516c>
_images/frame_plot_secondary_y_no_right.png

Suppressing Tick Resolution Adjustment

pandas includes automatic 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 [122]: plt.figure()
Out[122]: <matplotlib.figure.Figure at 0xa864098c>

In [123]: df.A.plot()
Out[123]: <matplotlib.axes._subplots.AxesSubplot at 0xa86bb36c>
_images/ser_plot_suppress.png

Using the x_compat parameter, you can suppress this behavior:

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

In [125]: df.A.plot(x_compat=True)
Out[125]: <matplotlib.axes._subplots.AxesSubplot at 0xaccabf0c>
_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 [126]: import pandas as pd

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

In [128]: 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

Subplots

Each Series in a DataFrame can be plotted on a different axis with the subplots keyword:

In [129]: df.plot(subplots=True, figsize=(6, 6));
_images/frame_plot_subplots.png

Using Layout and Targetting Multiple Axes

The layout of subplots can be specified by layout keyword. It can accept (rows, columns). The layout keyword can be used in hist and boxplot also. If input is invalid, ValueError will be raised.

The number of axes which can be contained by rows x columns specified by layout must be larger than the number of required subplots. If layout can contain more axes than required, blank axes are not drawn. Similar to a numpy array’s reshape method, you can use -1 for one dimension to automatically calculate the number of rows or columns needed, given the other.

In [130]: df.plot(subplots=True, layout=(3, 2), figsize=(6, 6), sharex=False);
_images/frame_plot_subplots_layout.png

The above example is identical to using

In [131]: df.plot(subplots=True, layout=(3, -1), figsize=(6, 6), sharex=False);

The required number of columns (2) is inferred from the number of series to plot and the given number of rows (3).

Also, you can pass multiple axes created beforehand as list-like via ax keyword. This allows to use more complicated layout. The passed axes must be the same number as the subplots being drawn.

When multiple axes are passed via ax keyword, layout, sharex and sharey keywords are ignored. These must be configured when creating axes.

In [132]: fig, axes = plt.subplots(4, 4, figsize=(6, 6));

In [133]: plt.subplots_adjust(wspace=0.5, hspace=0.5);

In [134]: target1 = [axes[0][0], axes[1][1], axes[2][2], axes[3][3]]

In [135]: target2 = [axes[3][0], axes[2][1], axes[1][2], axes[0][3]]

In [136]: df.plot(subplots=True, ax=target1, legend=False);

In [137]: (-df).plot(subplots=True, ax=target2, legend=False);
_images/frame_plot_subplots_multi_ax.png

Another option is passing an ax argument to Series.plot() to plot on a particular axis:

In [138]: fig, axes = plt.subplots(nrows=2, ncols=2)

In [139]: df['A'].plot(ax=axes[0,0]); axes[0,0].set_title('A');

In [140]: df['B'].plot(ax=axes[0,1]); axes[0,1].set_title('B');

In [141]: df['C'].plot(ax=axes[1,0]); axes[1,0].set_title('C');

In [142]: df['D'].plot(ax=axes[1,1]); axes[1,1].set_title('D');
_images/series_plot_multi.png

Plotting With Error Bars

New in version 0.14.

Plotting with error bars is now supported in the DataFrame.plot() and Series.plot()

Horizontal and vertical errorbars can be supplied to the xerr and yerr keyword arguments to plot(). The error values can be specified using a variety of formats.

  • As a DataFrame or dict of errors with column names matching the columns attribute of the plotting DataFrame or matching the name attribute of the Series
  • As a str indicating which of the columns of plotting DataFrame contain the error values
  • As raw values (list, tuple, or np.ndarray). Must be the same length as the plotting DataFrame/Series

Asymmetrical error bars are also supported, however raw error values must be provided in this case. For a M length Series, a Mx2 array should be provided indicating lower and upper (or left and right) errors. For a MxN DataFrame, asymmetrical errors should be in a Mx2xN array.

Here is an example of one way to easily plot group means with standard deviations from the raw data.

# Generate the data
In [143]: ix3 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], ['foo', 'foo', 'bar', 'bar', 'foo', 'foo', 'bar', 'bar']], names=['letter', 'word'])

In [144]: df3 = pd.DataFrame({'data1': [3, 2, 4, 3, 2, 4, 3, 2], 'data2': [6, 5, 7, 5, 4, 5, 6, 5]}, index=ix3)

# Group by index labels and take the means and standard deviations for each group
In [145]: gp3 = df3.groupby(level=('letter', 'word'))

In [146]: means = gp3.mean()

In [147]: errors = gp3.std()

In [148]: means
Out[148]: 
             data1  data2
letter word              
a      bar     3.5    6.0
       foo     2.5    5.5
b      bar     2.5    5.5
       foo     3.0    4.5

In [149]: errors
Out[149]: 
                data1     data2
letter word                    
a      bar   0.707107  1.414214
       foo   0.707107  0.707107
b      bar   0.707107  0.707107
       foo   1.414214  0.707107

# Plot
In [150]: fig, ax = plt.subplots()

In [151]: means.plot(yerr=errors, ax=ax, kind='bar')
Out[151]: <matplotlib.axes._subplots.AxesSubplot at 0xa5e82c2c>
_images/errorbar_example.png

Plotting Tables

New in version 0.14.

Plotting with matplotlib table is now supported in DataFrame.plot() and Series.plot() with a table keyword. The table keyword can accept bool, DataFrame or Series. The simple way to draw a table is to specify table=True. Data will be transposed to meet matplotlib’s default layout.

In [152]: fig, ax = plt.subplots(1, 1)

In [153]: df = DataFrame(rand(5, 3), columns=['a', 'b', 'c'])

In [154]: ax.get_xaxis().set_visible(False)   # Hide Ticks

In [155]: df.plot(table=True, ax=ax)
Out[155]: <matplotlib.axes._subplots.AxesSubplot at 0xa5e1a70c>
_images/line_plot_table_true.png

Also, you can pass different DataFrame or Series for table keyword. The data will be drawn as displayed in print method (not transposed automatically). If required, it should be transposed manually as below example.

In [156]: fig, ax = plt.subplots(1, 1)

In [157]: ax.get_xaxis().set_visible(False)   # Hide Ticks

In [158]: df.plot(table=np.round(df.T, 2), ax=ax)
Out[158]: <matplotlib.axes._subplots.AxesSubplot at 0xa5f28b4c>
_images/line_plot_table_data.png

Finally, there is a helper function pandas.tools.plotting.table to create a table from DataFrame and Series, and add it to an matplotlib.Axes. This function can accept keywords which matplotlib table has.

In [159]: from pandas.tools.plotting import table

In [160]: fig, ax = plt.subplots(1, 1)

In [161]: table(ax, np.round(df.describe(), 2),
   .....:       loc='upper right', colWidths=[0.2, 0.2, 0.2])
   .....: 
Out[161]: <matplotlib.table.Table at 0xa5cfea0c>

In [162]: df.plot(ax=ax, ylim=(0, 2), legend=None)
Out[162]: <matplotlib.axes._subplots.AxesSubplot at 0xa5d3f68c>
_images/line_plot_table_describe.png

Note: You can get table instances on the axes using axes.tables property for further decorations. See the matplotlib table documenation for more.

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 cubehelix colormap, we can simply pass 'cubehelix' to colormap=

In [163]: df = DataFrame(randn(1000, 10), index=ts.index)

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

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

In [166]: df.plot(colormap='cubehelix')
Out[166]: <matplotlib.axes._subplots.AxesSubplot at 0xa5ae020c>
_images/cubehelix.png

or we can pass the colormap itself

In [167]: from matplotlib import cm

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

In [169]: df.plot(colormap=cm.cubehelix)
Out[169]: <matplotlib.axes._subplots.AxesSubplot at 0xa5396bec>
_images/cubehelix_cm.png

Colormaps can also be used other plot types, like bar charts:

In [170]: dd = DataFrame(randn(10, 10)).applymap(abs)

In [171]: dd = dd.cumsum()

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

In [173]: dd.plot(kind='bar', colormap='Greens')
Out[173]: <matplotlib.axes._subplots.AxesSubplot at 0xa51ed04c>
_images/greens.png

Parallel coordinates charts:

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

In [175]: parallel_coordinates(data, 'Name', colormap='gist_rainbow')
Out[175]: <matplotlib.axes._subplots.AxesSubplot at 0xa4fd18ac>
_images/parallel_gist_rainbow.png

Andrews curves charts:

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

In [177]: andrews_curves(data, 'Name', colormap='winter')
Out[177]: <matplotlib.axes._subplots.AxesSubplot at 0xa4b3ff0c>
_images/andrews_curve_winter.png

Plotting directly with matplotlib

In some situations it may still be preferable or necessary to prepare plots directly with matplotlib, for instance when a certain type of plot or customization is not (yet) supported by pandas. Series and DataFrame objects behave like arrays and can therefore be passed directly to matplotlib functions without explicit casts.

pandas also automatically registers formatters and locators that recognize date indices, thereby extending date and time support to practically all plot types available in matplotlib. Although this formatting does not provide the same level of refinement you would get when plotting via pandas, it can be faster when plotting a large number of points.

Note

The speed up for large data sets only applies to pandas 0.14.0 and later.

In [178]: price = Series(randn(150).cumsum(),
   .....:                index=date_range('2000-1-1', periods=150, freq='B'))
   .....: 

In [179]: ma = pd.rolling_mean(price, 20)

In [180]: mstd = pd.rolling_std(price, 20)

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

In [182]: plt.plot(price.index, price, 'k')
Out[182]: [<matplotlib.lines.Line2D at 0xa47ec82c>]

In [183]: plt.plot(ma.index, ma, 'b')
Out[183]: [<matplotlib.lines.Line2D at 0xa460856c>]

In [184]: plt.fill_between(mstd.index, ma-2*mstd, ma+2*mstd, color='b', alpha=0.2)
Out[184]: <matplotlib.collections.PolyCollection at 0xa4608d2c>
_images/bollinger.png

Trellis plotting interface

Note

The tips data set can be downloaded here. Once you download it execute

from pandas import read_csv
tips_data = read_csv('tips.csv')

from the directory where you downloaded the file.

We import the rplot API:

In [185]: import pandas.tools.rplot as rplot

Examples

RPlot is a flexible API for producing Trellis plots. These plots allow you to arrange data in a rectangular grid by values of certain attributes.

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

In [187]: plot = rplot.RPlot(tips_data, x='total_bill', y='tip')

In [188]: plot.add(rplot.TrellisGrid(['sex', 'smoker']))

In [189]: plot.add(rplot.GeomHistogram())

In [190]: plot.render(plt.gcf())
Out[190]: <matplotlib.figure.Figure at 0xa480df0c>
_images/rplot1_tips.png

In the example above, data from the tips data set is arranged by the attributes ‘sex’ and ‘smoker’. Since both of those attributes can take on one of two values, the resulting grid has two columns and two rows. A histogram is displayed for each cell of the grid.

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

In [192]: plot = rplot.RPlot(tips_data, x='total_bill', y='tip')

In [193]: plot.add(rplot.TrellisGrid(['sex', 'smoker']))

In [194]: plot.add(rplot.GeomDensity())

In [195]: plot.render(plt.gcf())
Out[195]: <matplotlib.figure.Figure at 0xa42e05cc>
_images/rplot2_tips.png

Example above is the same as previous except the plot is set to kernel density estimation. This shows how easy it is to have different plots for the same Trellis structure.

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

In [197]: plot = rplot.RPlot(tips_data, x='total_bill', y='tip')

In [198]: plot.add(rplot.TrellisGrid(['sex', 'smoker']))

In [199]: plot.add(rplot.GeomScatter())

In [200]: plot.add(rplot.GeomPolyFit(degree=2))

In [201]: plot.render(plt.gcf())
Out[201]: <matplotlib.figure.Figure at 0xa45158cc>
_images/rplot3_tips.png

The plot above shows that it is possible to have two or more plots for the same data displayed on the same Trellis grid cell.

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

In [203]: plot = rplot.RPlot(tips_data, x='total_bill', y='tip')

In [204]: plot.add(rplot.TrellisGrid(['sex', 'smoker']))

In [205]: plot.add(rplot.GeomScatter())

In [206]: plot.add(rplot.GeomDensity2D())

In [207]: plot.render(plt.gcf())
Out[207]: <matplotlib.figure.Figure at 0xa419648c>
_images/rplot4_tips.png

Above is a similar plot but with 2D kernel density estimation plot superimposed.

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

In [209]: plot = rplot.RPlot(tips_data, x='total_bill', y='tip')

In [210]: plot.add(rplot.TrellisGrid(['sex', '.']))

In [211]: plot.add(rplot.GeomHistogram())

In [212]: plot.render(plt.gcf())
Out[212]: <matplotlib.figure.Figure at 0xa3af83ec>
_images/rplot5_tips.png

It is possible to only use one attribute for grouping data. The example above only uses ‘sex’ attribute. If the second grouping attribute is not specified, the plots will be arranged in a column.

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

In [214]: plot = rplot.RPlot(tips_data, x='total_bill', y='tip')

In [215]: plot.add(rplot.TrellisGrid(['.', 'smoker']))

In [216]: plot.add(rplot.GeomHistogram())

In [217]: plot.render(plt.gcf())
Out[217]: <matplotlib.figure.Figure at 0xa39e0e4c>
_images/rplot6_tips.png

If the first grouping attribute is not specified the plots will be arranged in a row.

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

In [219]: plot = rplot.RPlot(tips_data, x='total_bill', y='tip')

In [220]: plot.add(rplot.TrellisGrid(['.', 'smoker']))

In [221]: plot.add(rplot.GeomHistogram())

In [222]: plot = rplot.RPlot(tips_data, x='tip', y='total_bill')

In [223]: plot.add(rplot.TrellisGrid(['sex', 'smoker']))

In [224]: plot.add(rplot.GeomPoint(size=80.0, colour=rplot.ScaleRandomColour('day'), shape=rplot.ScaleShape('size'), alpha=1.0))

In [225]: plot.render(plt.gcf())
Out[225]: <matplotlib.figure.Figure at 0xa374fcec>
_images/rplot7_tips.png

As shown above, scatter plots are also possible. Scatter plots allow you to map various data attributes to graphical properties of the plot. In the example above the colour and shape of the scatter plot graphical objects is mapped to ‘day’ and ‘size’ attributes respectively. You use scale objects to specify these mappings. The list of scale classes is given below with initialization arguments for quick reference.

Scales

ScaleGradient(column, colour1, colour2)

This one allows you to map an attribute (specified by parameter column) value to the colour of a graphical object. The larger the value of the attribute the closer the colour will be to colour2, the smaller the value, the closer it will be to colour1.

ScaleGradient2(column, colour1, colour2, colour3)

The same as ScaleGradient but interpolates linearly between three colours instead of two.

ScaleSize(column, min_size, max_size, transform)

Map attribute value to size of the graphical object. Parameter min_size (default 5.0) is the minimum size of the graphical object, max_size (default 100.0) is the maximum size and transform is a one argument function that will be used to transform the attribute value (defaults to lambda x: x).

ScaleShape(column)

Map the shape of the object to attribute value. The attribute has to be categorical.

ScaleRandomColour(column)

Assign a random colour to a value of categorical attribute specified by column.