Pandas API#

If hvplot and pandas are both installed, then we can use the pandas.options.plotting.backend to control the output of pd.DataFrame.plot and pd.Series.plot. This notebook is meant to recreate the pandas visualization docs.

import numpy as np
import pandas as pd

pd.options.plotting.backend = 'holoviews'

Basic Plotting: plot#

The plot method on Series and DataFrame is just a simple wrapper around hvplot():

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()

If the index consists of dates, they will be sorted (as long as sort_date=True) and formatted the x-axis nicely as per above.

On DataFrame, plot() is a convenience to plot all of the columns with labels:

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot()

You can plot one column versus another using the x and y keywords in plot():

df3 = pd.DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
df3['A'] = pd.Series(list(range(len(df))))
df3.plot(x='A', y='B')

Note For more formatting and styling options, see formatting 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:

df.iloc[5].plot(kind='bar')

You can also create these other plots using the methods DataFrame.plot. instead of providing the kind keyword argument. This makes it easier to discover plot methods and the specific arguments they use:

In addition to these kinds, there are the DataFrame.hist(), and DataFrame.boxplot() methods, which use a separate interface.

Finally, there are several plotting functions in hvplot.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:

import holoviews as hv
df.iloc[5].plot.bar() * hv.HLine(0).opts(color='k')

Calling a DataFrame’s plot.bar() method produces a multiple bar plot:

df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2.plot.bar()

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

df2.plot.bar(stacked=True)

To get horizontal bar plots, use the barh method:

df2.plot.barh(stacked=True)

Histograms#

Histogram can be drawn by using the DataFrame.plot.hist() and Series.plot.hist() methods.

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

df4.plot.hist(alpha=0.5)

Using the matplotlib backend, histograms can be stacked using stacked=True; stacking is not yet supported in the holoviews backend. Bin size can be changed by bins keyword.

# Stacked not supported
df4.plot.hist(stacked=True, bins=20)
WARNING:param.main: Stacking for histograms is not yet implemented in holoviews. Use bar plots if stacking is required.

You can pass other keywords supported by matplotlib hist. For example, horizontal and cumulative histogram can be drawn by invert=True and cumulative=True.

df4['a'].plot.hist(invert=True, cumulative=True)

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

df['A'].diff().hist()

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

df.diff().hist(color='k', alpha=0.5, bins=50, subplots=True, width=300).cols(2)

The by keyword can be specified to plot grouped histograms:

# by does not support arrays, instead the array should be added as a column
data = pd.Series(np.random.randn(1000))
data = pd.DataFrame({'data': data, 'by_column': np.random.randint(0, 4, 1000)})
data.hist(by='by_column', width=300, subplots=True).cols(2)

Box Plots#

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).

df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
df.plot.box()

Using the matplotlib backend, boxplot can be colorized by passing color keyword. You can pass a dict whose keys are boxes, whiskers, medians and caps.

This behavior is not supported in the holoviews backend.

You can pass other keywords supported by holoviews boxplot. For example, horizontal and custom-positioned boxplot can be drawn by invert=True and positions keywords.

# positions not supported
df.plot.box(invert=True, positions=[1, 4, 5, 6, 8])
WARNING:param.main: positions option not found for box plot with bokeh; similar options include: ['projection']

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

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

df = pd.DataFrame(np.random.rand(10, 5))
df.boxplot()

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

df = pd.DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'])

df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])

df.boxplot(col='X')

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

df = pd.DataFrame(np.random.rand(10,3), columns=['Col1', 'Col2', 'Col3'])

df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])
df['Y'] = pd.Series(['A','B','A','B','A','B','A','B','A','B'])

df.boxplot(y=['Col1','Col2'], col='X', row='Y')
df_box = pd.DataFrame(np.random.randn(50, 2))
df_box['g'] = np.random.choice(['A', 'B'], size=50)
df_box.loc[df_box['g'] == 'B', 1] += 3
df_box.boxplot(row='g')

For more control over the ordering of the levels, we can perform a groupby on the data before plotting.

df_box.groupby('g').boxplot()

Area Plot#

You can create area plots with Series.plot.area() and DataFrame.plot.area(). Area plots are not 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.

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot.area(alpha=0.5)

To produce an stacked plot, pass stacked=True.

df.plot.area(stacked=True)

Scatter Plot#

Scatter plot can be drawn by using the DataFrame.plot.scatter() method. Scatter plot require that x and y be specified using the x and y keywords.

df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])
df.plot.scatter(x='a', y='b')

To plot multiple column groups in a single axes, repeat plot method and then use the overlay operator (*) to combine the plots. It is recommended to specify color and label keywords to distinguish each groups.

plot_1 = df.plot.scatter(x='a', y='b', color='DarkBlue', label='Group 1')
plot_2 = df.plot.scatter(x='c', y='d', color='DarkGreen', label='Group 2')

plot_1 * plot_2

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

df.plot.scatter(x='a', y='b', c='c', s=50)

You can pass other keywords supported by matplotlib scatter. The example below shows a bubble chart using a column of the DataFrame as the bubble size.

df.plot.scatter(x='a', y='b', s=df['c']*500)

The same effect can be accomplished using the scale option.

df.plot.scatter(x='a', y='b', s='c', scale=25)

Hexagonal Bin Plot#

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.

df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
df['b'] = df['b'] + np.arange(1000)

df.plot.hexbin(x='a', y='b', gridsize=25, width=500, height=400)

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.

df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
df['b'] = df['b'] = df['b'] + np.arange(1000)
df['z'] = np.random.uniform(0, 3, 1000)

df.plot.hexbin(x='a', y='b', C='z', reduce_function=np.max, gridsize=25, width=500, height=400)

Density Plot#

You can create density plots using the Series.plot.kde() and Data