Spaces:
Running
Running
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](https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html). | |
```python | |
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()`: | |
```python | |
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: | |
```python | |
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()`: | |
```python | |
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](#plot-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: | |
```python | |
df.iloc[5].plot(kind='bar') | |
``` | |
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 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 `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: | |
```python | |
import holoviews as hv | |
``` | |
```python | |
df.iloc[5].plot.bar() * hv.HLine(0).opts(color='k') | |
``` | |
Calling a DataFrame’s `plot.bar()` method produces a multiple bar plot: | |
```python | |
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`: | |
```python | |
df2.plot.bar(stacked=True) | |
``` | |
To get horizontal bar plots, use the `barh` method: | |
```python | |
df2.plot.barh(stacked=True) | |
``` | |
### Histograms | |
Histogram can be drawn by using the `DataFrame.plot.hist()` and `Series.plot.hist()` methods. | |
```python | |
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. | |
```python | |
# Stacked not supported | |
df4.plot.hist(stacked=True, bins=20) | |
``` | |
You can pass other keywords supported by matplotlib hist. For example, horizontal and cumulative histogram can be drawn by `invert=True` and `cumulative=True`. | |
```python | |
df4['a'].plot.hist(invert=True, cumulative=True) | |
``` | |
The existing interface `DataFrame.hist` to plot histogram still can be used. | |
```python | |
df['A'].diff().hist() | |
``` | |
`DataFrame.hist()` plots the histograms of the columns on multiple subplots: | |
```python | |
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: | |
```python | |
# 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). | |
```python | |
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. | |
```python | |
# positions not supported | |
df.plot.box(invert=True, positions=[1, 4, 5, 6, 8]) | |
``` | |
See the boxplot method and the matplotlib boxplot documentation for more. | |
The existing interface `DataFrame.boxplot` to plot boxplot still can be used. | |
```python | |
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, | |
```python | |
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: | |
```python | |
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') | |
``` | |
```python | |
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. | |
```python | |
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. | |
```python | |
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`. | |
```python | |
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. | |
```python | |
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. | |
```python | |
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: | |
```python | |
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. | |
```python | |
df.plot.scatter(x='a', y='b', s=df['c']*500) | |
``` | |
The same effect can be accomplished using the `scale` option. | |
```python | |
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. | |
```python | |
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. | |
```python | |
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 `DataFrame.plot.kde()` methods. | |
```python | |
ser = pd.Series(np.random.randn(1000)) | |
ser.plot.kde() | |
``` | |
### Pie plot | |
**NOT SUPPORTED** | |
## Plotting Tools | |
These functions can be imported from `hvplot.plotting` and take a `Series` or `DataFrame` as an argument. | |
### Scatter Matrix Plot | |
You can create a scatter plot matrix using the `scatter_matrix` function: | |
```python | |
import pandas as pd, numpy as np | |
``` | |
```python | |
from hvplot import scatter_matrix | |
df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd']) | |
scatter_matrix(df, alpha=0.2, diagonal='kde') | |
``` | |
Since scatter matrix plots may generate a large number of points (the one above renders 120,000 points!), you may want to take advantage of the power provided by [Datashader](https://datashader.org/) to rasterize the off-diagonal plots into a fixed-resolution representation: | |
```python | |
df = pd.DataFrame(np.random.randn(10000, 4), columns=['a', 'b', 'c', 'd']) | |
scatter_matrix(df, rasterize=True, dynspread=True) | |
``` | |
### 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. | |
```python | |
from bokeh.sampledata import iris | |
from hvplot import andrews_curves | |
data = iris.flowers | |
andrews_curves(data, 'species') | |
``` | |
### 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. | |
```python | |
from hvplot import parallel_coordinates | |
parallel_coordinates(data, 'species') | |
``` | |
### 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. | |
```python | |
from hvplot import lag_plot | |
data = pd.Series(0.1 * np.random.rand(1000) + | |
0.9 * np.sin(np.linspace(-99 * np.pi, 99 * np.pi, num=1000))) | |
lag_plot(data, width=400, height=400) | |
``` | |
### Autocorrelation Plot | |
**NOT SUPPORTED** | |
### Bootstrap Plot | |
**NOT SUPPORTED** | |
### RadViz | |
**NOT SUPPORTED** | |
## Plot Formatting | |
### General plot style arguments | |
Most plotting methods have a set of keyword arguments that control the layout and formatting of the returned plot: | |
```python | |
ts.plot(c='k', line_dash='dashed', label='Series') | |
``` | |
For each kind of plot (e.g. *line*, *bar*, *scatter*) any additional arguments keywords are passed along to the corresponding holoviews object (`hv.Curve`, `hv.Bar`, `hv.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. You can also control the placement of the legend using the same `legend` argument set to one of: 'top_right', 'top_left', 'bottom_left', 'bottom_right', 'right', 'left', 'top', or 'bottom'. | |
```python | |
df = pd.DataFrame(np.random.randn(1000, 4), | |
index=ts.index, columns=list('ABCD')) | |
df = df.cumsum() | |
df.plot(legend=False) | |
``` | |
```python | |
df.plot(legend='top_left') | |
``` | |
### Scales | |
You may pass `logy` to get a log-scale Y axis, similarly use `logx` to get a log-scale on the X axis or `logz` to get a log-scale on the color axis. | |
```python | |
ts = pd.Series(np.random.randn(1000), | |
index=pd.date_range('1/1/2000', periods=1000)) | |
ts = np.exp(ts.cumsum()) | |
ts.plot(logy=True) | |
``` | |
```python | |
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, logz=True) | |
``` | |
### Plotting on a Secondary Y-axis | |
**NOT SUPPORTED** | |
### 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 labeling is performed: | |
```python | |
df = pd.DataFrame(np.random.randn(1000, 4), | |
index=ts.index, columns=list('ABCD')) | |
df = df.cumsum() | |
df.A.plot() | |
``` | |
Formatters can be set using format strings, by declaring bokeh TickFormatters, or using custom functions. See [HoloViews Tick Docs](https://holoviews.org/user_guide/Customizing_Plots.html#Axis-ticks) for more information. | |
```python | |
from bokeh.models.formatters import DatetimeTickFormatter | |
formatter = DatetimeTickFormatter(months='%b %Y') | |
``` | |
```python | |
df.A.plot(yformatter='$%.2f', xformatter=formatter) | |
``` | |
### Subplots | |
Each `Series` in a `DataFrame` can be plotted on a different axis with the `subplots` keyword: | |
```python | |
df = pd.DataFrame(np.random.randn(1000, 4), | |
index=ts.index, columns=list('ABCD')) | |
df = df.cumsum() | |
df.plot(subplots=True, height=150).cols(1) | |
``` | |
### Controlling layout and targeting multiple axes | |
The layout of subplots can be specified using `.cols(n)`. | |
```python | |
df.plot(subplots=True, shared_axes=False, width=150).cols(3) | |
``` | |
### Plotting with error bars | |
Plotting with error bars is *not* supported in `DataFrame.plot()` and `Series.plot()`. To add errorbars, users should fall back to using hvplot directly. | |
```python | |
import hvplot.pandas # noqa | |
``` | |
```python | |
df3 = pd.DataFrame({'data1': [3, 2, 4, 3, 2, 4, 3, 2], | |
'data2': [6, 5, 7, 5, 4, 5, 6, 5]}) | |
mean_std = pd.DataFrame({'mean': df3.mean(), 'std': df3.std()}) | |
mean_std | |
``` | |
```python | |
(mean_std.plot.bar(y='mean', alpha=0.7) * \ | |
mean_std.hvplot.errorbars(x='index', y='mean', yerr1='std') | |
).opts(show_legend=False).redim.range(mean=(0, 6.5)) | |
``` | |
### Plotting tables | |
The matplotlib backend includes support for the `table` keyword in `DataFrame.plot()` and `Series.plot()`. This same effect can be accomplished with holoviews by using `hvplot.table` and creating a layout of the resulting plots. | |
```python | |
df = pd.DataFrame(np.random.rand(5, 3), columns=['a', 'b', 'c']) | |
(df.plot(xaxis=False, legend='top_right') + \ | |
df.T.hvplot.table()).cols(1) | |
``` | |
### 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 colormap or a string that is a name of a colormap. | |
To use the cubehelix colormap, we can pass `colormap='cubehelix'`. | |
```python | |
df = pd.DataFrame(np.random.randn(1000, 10), index=ts.index) | |
df = df.cumsum() | |
df.plot(colormap='cubehelix') | |
``` | |
Colormaps can also be used with other plot types, like bar charts: | |
```python | |
dd = pd.DataFrame(np.random.randn(10, 10)).applymap(abs) | |
dd = dd.cumsum() | |
dd.plot.bar(colormap='Greens') | |
``` | |
Parallel coordinates charts: | |
```python | |
from bokeh.sampledata import iris | |
from hvplot import parallel_coordinates, andrews_curves | |
data = iris.flowers | |
parallel_coordinates(data, 'species', colormap='gist_rainbow') | |
``` | |
Andrews curves charts: | |
```python | |
andrews_curves(data, 'species', colormap='winter') | |
``` | |
## Plotting directly with holoviews | |
In some situations it may still be preferable or necessary to prepare plots directly with hvplot or holoviews, 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 holoviews functions without explicit casts. | |
```python | |
import holoviews as hv | |
price = pd.Series(np.random.randn(150).cumsum(), | |
index=pd.date_range('2000-1-1', periods=150, freq='B'), name='price') | |
ma = price.rolling(20).mean() | |
mstd = price.rolling(20).std() | |
price.plot(c='k') * ma.plot(c='b', label='mean') * \ | |
hv.Area((mstd.index, ma - 2 * mstd, ma + 2 * mstd), | |
vdims=['y', 'y2']).opts(color='b', alpha=0.2) | |
``` | |