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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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)
```