Updated On : Nov-12,2022 Time Investment : ~45 mins

Getting Started with Holoviews - Basic Plotting

Data Visualization is one of the best ways to present and analyze data. Python has many useful data visualization libraries like matplotlib, seaborn, bokeh, plotly, Altair, bqplot, plotnine, etc.

Charts created using libraries like matplotlib and seaborn are static whereas libraries like bokeh and plotly generate interactive charts.

All of these libraries require little learning curves to start working with them.

Holoviews is an open-source python plotting library designed to make plotting easy and intuitive. Holoviews is designed on top of matplotlib, bokeh, and plotly. It reduces the number of lines of code required for plotting.

It provides a high-level interface on matplotlib, bokeh, and plotly that makes plotting interactive plots quite an easy task. This frees us from worrying about getting charts right and lets us concentrate on actual analysis.

What Can You Learn From This Article?

As a part of this tutorial, we have explained how you can create interactive charts using Python data viz library holoviews in Jupyter notebook. Tutorial covers basic charts like scatter plots, bar charts, histograms, etc. Tutorial even explains how we can switch between plotting backends (bokeh, matplotlib & plotly) and how to combine charts.

Below, we have listed important sections of Tutorial to give an overview of the material covered.

Important Sections Of Tutorial

  1. Basic Charts with One Line of Code
    • Loading Holoviews (Bokeh Backend)
    • Scatter Plot
    • Bar Chart
    • Histogram
    • BoxWhisker
    • Elements
  2. How to Change Plotting Backend?
    • Matplotlib Backend
    • Plotly Backend
  3. Modify Charts by Providing Options
  4. Merge Charts
  5. More Charts
    • Stacked Bar Chart
    • Grouped Bar Chart
    • Heatmap
    • Multiple Lines Chart
    • Area Chart
    • Box Whisker Plot
    • Violin Chart
    • Histograms
    • Hexbin Plot

Holoviews Video Tutorial

Please feel free to check below video tutorial if feel comfortable learning through videos. We have covered three different chart types in video. But in this tutorial, we have covered many different chart types.



Below, we have imported necessary Python libraries that we'll use in our tutorial. We have also printed the versions of those libraries that we have used.

import pandas as pd
import numpy as np

pd.set_option("display.max_columns", 30)
import holoviews as hv

print("Holoviews Version : {}".format(hv.__version__))
Holoviews Version : 1.15.1

Load Datasets

Below, we have loaded two datasets that we'll use in our tutorial.

  • Wine Dataset: The wine dataset is available from scikit-learn. It has 13 features and a target variable with 3 different classes of wine.
  • Apple OHLC Dataset: It has OHLC data about apple stock for 1 year downloaded from Yahoo finance as a CSV file.

We'll keep both datasets in pandas dataframe so that it becomes easily available for plotting and manipulation.

Wine Dataset

from sklearn.datasets import load_wine

wine = load_wine()

wine_df = pd.DataFrame(wine.data, columns = wine.feature_names)
wine_df["Target"] = wine.target
wine_df["Target"] = ["Class_1" if typ==0 else "Class_2" if typ==1 else "Class_3"  for typ in wine_df["Target"]]

wine_df.head()
alcohol malic_acid ash alcalinity_of_ash magnesium total_phenols flavanoids nonflavanoid_phenols proanthocyanins color_intensity hue od280/od315_of_diluted_wines proline Target
0 14.23 1.71 2.43 15.6 127.0 2.80 3.06 0.28 2.29 5.64 1.04 3.92 1065.0 Class_1
1 13.20 1.78 2.14 11.2 100.0 2.65 2.76 0.26 1.28 4.38 1.05 3.40 1050.0 Class_1
2 13.16 2.36 2.67 18.6 101.0 2.80 3.24 0.30 2.81 5.68 1.03 3.17 1185.0 Class_1
3 14.37 1.95 2.50 16.8 113.0 3.85 3.49 0.24 2.18 7.80 0.86 3.45 1480.0 Class_1
4 13.24 2.59 2.87 21.0 118.0 2.80 2.69 0.39 1.82 4.32 1.04 2.93 735.0 Class_1

Apple OHLC Dataset

apple_df = pd.read_csv("~/datasets/AAPL.csv")
apple_df["Date"] = pd.to_datetime(apple_df["Date"])

apple_df.head()
Date Open High Low Close Adj Close Volume
0 2019-04-05 196.449997 197.100006 195.929993 197.000000 194.454758 18526600
1 2019-04-08 196.419998 200.229996 196.339996 200.100006 197.514709 25881700
2 2019-04-09 200.320007 202.850006 199.229996 199.500000 196.922470 35768200
3 2019-04-10 198.679993 200.740005 198.179993 200.619995 198.027985 21695300
4 2019-04-11 200.850006 201.000000 198.440002 198.949997 196.379578 20900800

1. Basic Plots

We'll start plotting a few basic plots like scatter plots, bar charts, histograms, etc. We'll then further explore holoviews options.

1.1 Loading Holoviews [Bokeh Backend]

We'll start importing holoviews and then set its backend using the hv.extension() method.

We'll be using bokeh and matplotlib backends interchangeably to explain how the same holoviews code can be used for both(matplotlib & bokeh).

hv.extension("bokeh")

Getting Started with holoviews

We can provide more than one backend (e.g, hv.extension("bokeh", "matplotlib")) separated by comma as well. Later on, we can use backend parameter of opts() method (used to set chart options) to create chart using that particular backend.

1.2 Scatter Plot

We are plotting the scatter plot below to show the relationship between alcohol and malic_acid values in wine. We can see that just one line of code is enough to create a simple interactive graph. We need to pass the first argument as a dataframe that maintains data and then kdims and vdims to represent x and y of a graph.

scat = hv.Scatter(wine_df, kdims="alcohol", vdims="malic_acid", label="alcohol vs malic_acid scatter")

scat

Getting Started with holoviews

Below, we have printed holoviews object (scatter plot) which we created above to see their structure further which can give us meaningful insights.

print(scat)

Getting Started with holoviews

We can see that all of the plot object printed kdims (key dimensions) in square brackets and all vdims (value dimensions) in parenthesis.

Holoviews sees kdims as primary dimensions which is must to generate plot and vdims as additional secondary dimensions which can add further to primary dimensions.

Holoviews plots need just primary dimensions for plotting purposes and if secondary dimensions do not provide meaningful plotting information then it ignores it.

1.3 Bar Chart

To plot the bar chart, we are grouping dataframe by Target variable, taking an average of all columns, and then filtering dataframe with only one column named malic_acid. We then just pass that to the Bars method to generate a bar chart.

avg_wine_df = wine_df.groupby("Target").mean()

avg_wine_df
alcohol malic_acid ash alcalinity_of_ash magnesium total_phenols flavanoids nonflavanoid_phenols proanthocyanins color_intensity hue od280/od315_of_diluted_wines proline
Target
Class_1 13.744746 2.010678 2.455593 17.037288 106.338983 2.840169 2.982373 0.290000 1.899322 5.528305 1.062034 3.157797 1115.711864
Class_2 12.278732 1.932676 2.244789 20.238028 94.549296 2.258873 2.080845 0.363662 1.630282 3.086620 1.056282 2.785352 519.507042
Class_3 13.153750 3.333750 2.437083 21.416667 99.312500 1.678750 0.781458 0.447500 1.153542 7.396250 0.682708 1.683542 629.895833
bar = hv.Bars(avg_wine_df[["malic_acid"]], label="Average Malic Acid Per Wine Class")

bar

Getting Started with holoviews

print(bar)

Getting Started with holoviews

1.4 Histogram

We are using a numpy histogram method to generate histogram entries. We pass it values of column magnesium and it returns and position of bins and value for each bin. We then pass it to the Histogram method of holoviews to generate a histogram.

hist = hv.Histogram(np.histogram(wine_df['magnesium'], bins=24), kdims="magnesium", label="magnesium histogram")

hist

Getting Started with holoviews

print(hist)

Getting Started with holoviews

1.5 BoxWhisker

We can generate box whisker plot easily by passing kdims=Target and vdims=total_pheonols. It'll generate distribution of total_phenols values per each wine class.

box_whisker = hv.BoxWhisker(wine_df, kdims="Target", vdims="total_phenols" , label="total_phenols per wine class distribution")

box_whisker

Getting Started with holoviews

print(box_whisker)

Getting Started with holoviews

1.6 Elements

We can also generate basic line charts and points chart using holoviews as described below.

curve = hv.Curve(apple_df, kdims="Date", vdims="Close")

curve

Getting Started with holoviews

print(curve)

Getting Started with holoviews

points = hv.Points(wine_df, kdims=["color_intensity", "hue"], label="color_intensity vs hue scatter")

points

Getting Started with holoviews

print(points)

Getting Started with holoviews

We can notice by looking at all the above graphs is generated using bokeh. It shows the bokeh symbol as well in the toolbar to confirm it.

2. How to Change Ploting Backend?

As we already discussed above that holoviews just maintains plotting metadata and uses underlying back-end python library for plotting, we'll now explain below on how can we change different back-ends according to our needs. It won't require any code change in plotting graphs to change back-end.

2.1 Matplotlib Backend

We can change backend by simply calling the extension() method and passing it a new backend. It'll then start using that backend for plotting. Below we have initialized holoviews with matplotlib backend.

hv.extension("matplotlib")

Getting Started with holoviews

Scatter Plot

We can see that we have clearly used the same code for generating a matplotlib graph without changing code even a little bit. We might need to sometime change some argument of code as parameters might be different for the different backend but in the majority of cases, it'll be almost the same.

scat = hv.Scatter(wine_df, kdims="alcohol", vdims="malic_acid", label="alcohol vs malic_acid scatter")

scat

Getting Started with holoviews

2.2 Plotly Backend

We'll now initialize holoviews using plotly backend and plot various graphs.

hv.extension("plotly")

Getting Started with holoviews

Bar Chart

bar = hv.Bars(wine_df.groupby("Target").mean()[["malic_acid"]], label="Average Malic Acid Per Wine Class")

bar

Getting Started with holoviews Plotly Graphs

3. Modify Charts by Providing Options

We can notice from the majority of the above graphs that the majority of plotting options like height, width, axes labels, ticks limits, colors, etc. are default selected by holoviews.

But what if a person needs control over it and needs to change various options according to it needs?

Holoviews provided two very easy ways to provide configuration options that will be passed to underlying libraries.

  1. opts() Method
  2. %%opts Magic Command

It'll also ignore options which do not available in the underlying library by giving warnings.

We'll start setting our extension as bokeh again.

hv.extension("bokeh")

Getting Started with holoviews

3.1 Specify Chart Options using "%%opts" Magic Command

The first way of providing configuration options to graph is by using jupyter notebook magic command %%opts.

We need to give a plot object to which we need to apply the configuration options followed by a magic command.

Holoviews has divided configuration options into two categories primary and secondary here as well.

All primary options are about to look of a graph like xlabel, ylabel, height, width, etc.

All secondary options are about actual data plotting options like the size of points, alpha, color, width of the bar, etc.

If you are someone new to concept of magic commands in Jupyter notebook then please check below link. We have a small tutorial explaining majority of magic commands available in Jupyter notebook.

%%opts Scatter [tools=["hover"] xlabel="Alcohol" ylabel="Malic Acid" height=400 width=600](alpha=0.7 size=15 color="green" line_color="black")

scat = hv.Scatter(wine_df, kdims="alcohol", vdims="malic_acid", label="Alcohol vs Malic Acid Relation")

scat

Getting Started with holoviews

The below graph makes use of a hover color option which changes bar color when the mouse pointer is hovered over it and highlights it.

%%opts Bars [height=400 width=600 tools=["hover"] bgcolor="grey" xlabel="Wine Class" ylabel="Malic Acid" ylim=(0.0, 3.5)]
%%opts Bars (color="black" hover_color="red" bar_width=0.5)

bar = hv.Bars(wine_df.groupby("Target").mean()[["malic_acid"]], label="Average Malic Acid Per Wine Class")

bar

Getting Started with holoviews

3.2 Specify Chart Options using "opts()" Method

Below, we have explained another way of passing configuration options. We can also call opts() or options() method on graph object and pass it all parameters as per need.

scat = hv.Scatter(wine_df, kdims="alcohol", vdims="malic_acid", label="Alcohol vs Malic Acid Relation")

scat.opts(xlabel="Alcohol",
          ylabel="Malic Acid",
          height=400, width=600,
          tools=["hover"],
          alpha=0.7, size=15,
          color="purple", line_color="black")

Getting Started with holoviews

4. Merge Charts

We have explained how to create basic graphs. We'll now explain how can we merge more than one graph into holoviews.

Holoviews lets us merge graph objects using 2 operations

  1. + - It merges graphs by putting them next to each other
  2. * - It overlays graphs on one another to create one single graph combining all individuals.

We'll start merging three bar charts with + operation.

%%opts Bars (color="limegreen")

bar1 = hv.Bars(avg_wine_df[["malic_acid"]], label="Average Malic Acid Per Class")
bar2 = hv.Bars(avg_wine_df[["ash"]], label="Average Ash Per Class")
bar3 = hv.Bars(avg_wine_df[["alcohol"]], label="Average Alcohol Per Class")

bars = bar1 + bar2 + bar3

bars

Getting Started with holoviews

print(bars)

Getting Started with holoviews

By printing bars object, we can see that it’s of type Layout.

Layout objects are responsible for maintaining the layout of the charts. The above layout is set out as a grid of 1 row and 3 columns(1x3).

We can even access individual elements as well by simply following dot notation.

bars.Bars.Average_Alcohol_Per_Class

Getting Started with holoviews

We'll now explain another merge operation using *.

We'll be using * to overlay 3 scatter plots over one another. We are creating 3 scatter plot of alcohol vs malic_acid for 3 different wine categories.

We'll then overlay them on each other to create a single scatter plot.

%%opts Scatter [tools=["hover"] xlabel="Alcohol" ylabel="Malic Acid" height=400 width=600 xlim=(10.8, 15.0) ylim=(0.0,6.0) title="Alcohol vs malic acid color-encoded by wine category"]
%%opts Scatter (alpha=0.7 size=15 line_color="black")

scat1 = hv.Scatter(wine_df[wine_df["Target"] == "Class_1"], kdims="alcohol", vdims="malic_acid")
scat2 = hv.Scatter(wine_df[wine_df["Target"] == "Class_2"], kdims="alcohol", vdims="malic_acid")
scat3 = hv.Scatter(wine_df[wine_df["Target"] == "Class_3"], kdims="alcohol", vdims="malic_acid")

scatters = (scat1 * scat2 * scat3)

scatters

Getting Started with holoviews

print(scatters)

Getting Started with holoviews

By printing the scatters object, we can see that its type is Overlay.

We can access individual elements of Overlay by simply following dot notation.

scatters.Scatter.II

Getting Started with holoviews

The below example explains, how can we organize a Layout object created when we merge more than one graph using + operation.

We'll be using it's cols() method passing it a number of columns to organize graphs.

We have below created 4 graphs and passed 2 as cols value which will organize graphs into 2 columns instead of just putting them next to each other.

%%opts BoxWhisker [tools=["hover"]] (box_fill_color="tomato" whisker_color="limegreen")

box_whisker1 = hv.BoxWhisker(wine_df, kdims="Target", vdims="total_phenols" , label="total_phenols per wine class distribution")
box_whisker2 = hv.BoxWhisker(wine_df, kdims="Target", vdims="ash" , label="ash per wine class distribution")
box_whisker3 = hv.BoxWhisker(wine_df, kdims="Target", vdims="alcohol" , label="alcohol per wine class distribution")
box_whisker4 = hv.BoxWhisker(wine_df, kdims="Target", vdims="malic_acid" , label="malic_acid per wine class distribution")

(box_whisker1 + box_whisker2 + box_whisker3 + box_whisker4).cols(2)

Getting Started with holoviews

The simple process of merging more than 1 graph explained above reduced a lot of coding from the developer side. We can even mix + and * operations into one expression to create a complicated figure.

5. More Charts

In this section, we'll explain few more charts that are commonly used when doing data analysis. We'll be creating those charts using various concepts we discussed till now.

5.1 Stacked Bar Chart

Here, we have explained how to create stacked bar chart using holoviews. We have created a stacked bar chart showing average ingredients used per wine type.

Below, we have first melted our average wine dataframe to create new dataframe that we'll use for creating stacked bar chart.

In the next cell, we have created a stacked bar chart using Bars() method of holoviews. We have selected 5 ingredients to be kept in chart instead of all of them. We have provided wine type and ingredient names as kdims and average ingredient value as vdims.

We have set various chart attributes as well using %%opts magic command. In order to create stacked bar chart, we have set stacked option to True.

melted_avg_wine_df = avg_wine_df.reset_index().melt(id_vars=["Target"], var_name="Ingredients", value_name="Avg Value")

melted_avg_wine_df.head()
Target Ingredients Avg Value
0 Class_1 alcohol 13.744746
1 Class_2 alcohol 12.278732
2 Class_3 alcohol 13.153750
3 Class_1 malic_acid 2.010678
4 Class_2 malic_acid 1.932676
%%opts Bars [stacked=True  width=600 height=400 tools=["hover"] title="Average Ingredients Per Wine Type Stacked"]
%%opts Bars [show_legend=True legend_position="right" legend_opts={"title": "Ingredients"}]
%%opts Bars [ylabel="Avg Ingredient"]

ingredients = ["malic_acid", "ash", "total_phenols", "hue", "proanthocyanins"]

bar = hv.Bars(melted_avg_wine_df[melted_avg_wine_df["Ingredients"].isin(ingredients)],
               kdims=["Target", "Ingredients"],
               vdims=["Avg Value"])

bar

Getting Started with holoviews

5.2 Grouped Bar Chart

Below, we have created a grouped bar chart showing average ingredients used per wine type using holoviews. The code is exactly same as previous example with only one change.

We have not set stacked option to True in this case. By default, holoviews will create grouped bar charts. We need to tell it to stack bars if we want to explicitly.

%%opts Bars [width=700 height=450 tools=["hover"] title="Average Ingredients Per Wine Type Grouped"]
%%opts Bars [show_legend=True legend_position="top" legend_opts={"title": "Ingredients"}]
%%opts Bars [xrotation=45 xlabel="Wine Type, Ingredients"]

ingredients = ["malic_acid", "ash", "total_phenols", "hue", "proanthocyanins"]

bar = hv.Bars(melted_avg_wine_df[melted_avg_wine_df["Ingredients"].isin(ingredients)],
               kdims=["Target", "Ingredients"],
               vdims=["Avg Value"])

bar

Getting Started with holoviews

5.3 Heatmap

In this section, we have explained how to create heatmap using holoviews. We have created a heatmap showing correlation between ingredients of wine dataset.

Below, we have first calculated correlation by calling corr() method on wine dataframe.

Then, in the next cell, we have melted correlation dataframe for using it with holoviews.

In the cell below, we have created a heatmap using the Heatmap() method of holoviews. We have provided ingredient names as kdims and correlation values as vdims.

wine_corr = wine_df.corr().reset_index().rename(columns={"index": "Ingredients1"})

wine_corr
Ingredients1 alcohol malic_acid ash alcalinity_of_ash magnesium total_phenols flavanoids nonflavanoid_phenols proanthocyanins color_intensity hue od280/od315_of_diluted_wines proline
0 alcohol 1.000000 0.094397 0.211545 -0.310235 0.270798 0.289101 0.236815 -0.155929 0.136698 0.546364 -0.071747 0.072343 0.643720
1 malic_acid 0.094397 1.000000 0.164045 0.288500 -0.054575 -0.335167 -0.411007 0.292977 -0.220746 0.248985 -0.561296 -0.368710 -0.192011
2 ash 0.211545 0.164045 1.000000 0.443367 0.286587 0.128980 0.115077 0.186230 0.009652 0.258887 -0.074667 0.003911 0.223626
3 alcalinity_of_ash -0.310235 0.288500 0.443367 1.000000 -0.083333 -0.321113 -0.351370 0.361922 -0.197327 0.018732 -0.273955 -0.276769 -0.440597
4 magnesium 0.270798 -0.054575 0.286587 -0.083333 1.000000 0.214401 0.195784 -0.256294 0.236441 0.199950 0.055398 0.066004 0.393351
5 total_phenols 0.289101 -0.335167 0.128980 -0.321113 0.214401 1.000000 0.864564 -0.449935 0.612413 -0.055136 0.433681 0.699949 0.498115
6 flavanoids 0.236815 -0.411007 0.115077 -0.351370 0.195784 0.864564 1.000000 -0.537900 0.652692 -0.172379 0.543479 0.787194 0.494193
7 nonflavanoid_phenols -0.155929 0.292977 0.186230 0.361922 -0.256294 -0.449935 -0.537900 1.000000 -0.365845 0.139057 -0.262640 -0.503270 -0.311385
8 proanthocyanins 0.136698 -0.220746 0.009652 -0.197327 0.236441 0.612413 0.652692 -0.365845 1.000000 -0.025250 0.295544 0.519067 0.330417
9 color_intensity 0.546364 0.248985 0.258887 0.018732 0.199950 -0.055136 -0.172379 0.139057 -0.025250 1.000000 -0.521813 -0.428815 0.316100
10 hue -0.071747 -0.561296 -0.074667 -0.273955 0.055398 0.433681 0.543479 -0.262640 0.295544 -0.521813 1.000000 0.565468 0.236183
11 od280/od315_of_diluted_wines 0.072343 -0.368710 0.003911 -0.276769 0.066004 0.699949 0.787194 -0.503270 0.519067 -0.428815 0.565468 1.000000 0.312761
12 proline 0.643720 -0.192011 0.223626 -0.440597 0.393351 0.498115 0.494193 -0.311385 0.330417 0.316100 0.236183 0.312761 1.000000
melted_wine_corr = wine_corr.melt(id_vars=["Ingredients1"],
                                  var_name="Ingredients2", value_name="Ingredient Value")

melted_wine_corr.head()
Ingredients1 Ingredients2 Ingredient Value
0 alcohol alcohol 1.000000
1 malic_acid alcohol 0.094397
2 ash alcohol 0.211545
3 alcalinity_of_ash alcohol -0.310235
4 magnesium alcohol 0.270798
%%opts HeatMap [height=600 width=700 title="Wine Ingredients Correlation" tools=["hover"]]
%%opts HeatMap [xrotation=45 colorbar=True xlabel="" ylabel="" ]
%%opts HeatMap (cmap="Purples")

hv.HeatMap(melted_wine_corr, kdims=["Ingredients1", "Ingredients2"], vdims="Ingredient Value")

Getting Started with holoviews

5.4 Multiple Lines Chart

In this section, we have explained how to create line chart with multiple lines using holoviews. We have created a line chart showing open, high, low, and close prices of apple stock dataframe we loaded earlier.

We created line chart for all 4 lines separately and merged them.

%%opts Curve [height=500 width=700 tools=["hover"] title="Apple OHLC Prices"]

line1 = hv.Curve(apple_df, kdims="Date", vdims="Open", label="Open Prices")
line2 = hv.Curve(apple_df, kdims="Date", vdims="High", label="High Prices")
line3 = hv.Curve(apple_df, kdims="Date", vdims="Low", label="Low Prices")
line4 = hv.Curve(apple_df, kdims="Date", vdims="Close", label="Close Prices")

line1 * line2 * line3 * line4

Getting Started with holoviews

5.5 Area Charts

In this section, we have explained how you can create an area chart using holoviews. We have created an area chart showing the area covered by close price of apple stock.

The area chart is created using Area() method of holoviews. You can create more than one area chart and merge them like line chart we explained in previous section.

%%opts Area [height=500 width=700 title="Apple Close Prices" ]
%%opts Area (fill_alpha=0.5)

area = hv.Area(apple_df, kdims="Date", vdims="Close", label="Close Prices")

area

Getting Started with holoviews

5.6 Box Whisker Plots

In this section, we have explained how you can create box whisker plot using holoviews. We have created first box whisker plot showing concentration of values of few ingredients.

In order to create a box whisker plot, we have first melted our original wine dataframe below. Then, we have created box plot for ingredients separately by calling BoxWhisker() method of holoviews.

At last, we have merged box whisker plots of all ingredients to create one box whisker plot.

melted_wine_df = wine_df.melt(id_vars=["Target"], var_name="Ingredients")

melted_wine_df = melted_wine_df[melted_wine_df["Ingredients"].isin(["alcohol", "malic_acid", "ash", "total_phenols", "flavanoids"])]

melted_wine_df.head()
Target Ingredients value
0 Class_1 alcohol 14.23
1 Class_1 alcohol 13.20
2 Class_1 alcohol 13.16
3 Class_1 alcohol 14.37
4 Class_1 alcohol 13.24
%%opts BoxWhisker [height=500 width=700 title="Wine Ingredients Distribution"]

box1 = hv.BoxWhisker(melted_wine_df[melted_wine_df["Ingredients"]=="alcohol"], kdims="Ingredients", vdims="value")
box2 = hv.BoxWhisker(melted_wine_df[melted_wine_df["Ingredients"]=="malic_acid"], kdims="Ingredients", vdims="value")
box3 = hv.BoxWhisker(melted_wine_df[melted_wine_df["Ingredients"]=="ash"], kdims="Ingredients", vdims="value")
box4 = hv.BoxWhisker(melted_wine_df[melted_wine_df["Ingredients"]=="total_phenols"], kdims="Ingredients", vdims="value")
box5 = hv.BoxWhisker(melted_wine_df[melted_wine_df["Ingredients"]=="flavanoids"], kdims="Ingredients", vdims="value")

box1 * box2 * box3 * box4 * box5

Getting Started with holoviews

Below, we have created another example showing how we can create box whisker plot showing ingredients concentration based on wine type. You can notice that kdims is set differently in this case.

%%opts BoxWhisker [height=500 width=700 title="Wine Ingredients Distribution Per Wine Type"]
%%opts BoxWhisker [xrotation=45]
%%opts BoxWhisker (box_color="Ingredients" box_cmap="Category20")

box1 = hv.BoxWhisker(melted_wine_df, kdims=["Target", "Ingredients"], vdims="value")

box1

Getting Started with holoviews

5.7 Violin Charts

In this section, we have explained how to create violin plots using holoviews. We have created violin chart showing concentration of ingredients.

In order to create a violin chart, we have used the same melted dataframe that we created in box whisker plots. We have created violin chart by providing melted dataframe to Violin() method of holoviews.

%%opts Violin [height=500 width=700 title="Wine Ingredients Distribution" show_legend=True]
%%opts Violin (violin_color="Ingredients")

violin1 = hv.Violin(melted_wine_df, kdims="Ingredients", vdims="value")

violin1

Getting Started with holoviews

Below, we have created another example of violin chart showing the concentration of ingredients based on wine type.

%%opts Violin [height=500 width=700 title="Wine Ingredients Distribution Per Wine Type" show_legend=True]
%%opts Violin [xrotation=45]
%%opts Violin (violin_color="Ingredients")

violin = hv.Violin(melted_wine_df, kdims=["Target", "Ingredients"], vdims="value")

violin

Getting Started with holoviews

5.8 Histograms

In this section, we have explained how we can create histograms of more than one data variable using holoviews. We have created a histogram of few ingredients.

We have created histogram of ingredients separately as we had explained in the basic charts section and then combined them to create a single histogram.

%%opts Histogram [height=500 width=800 title="Ingredients Histogram" show_legend=True]
%%opts Histogram (alpha=0.6)

hist1 = hv.Histogram(np.histogram(wine_df['malic_acid'], bins=24), kdims="malic_acid", label="Malic Acid histogram")
hist2 = hv.Histogram(np.histogram(wine_df['alcohol'], bins=24), kdims="magnesium", label="Alcohol histogram")
hist3 = hv.Histogram(np.histogram(wine_df['ash'], bins=24), kdims="ash", label="Ash histogram")
hist4 = hv.Histogram(np.histogram(wine_df['color_intensity'], bins=24), kdims="color_intensity", label="Total Phenols histogram")

hist1 * hist2 * hist3 * hist4

Getting Started with holoviews

Below, we have created another histogram showing distribution of alcohol per wine type.

%%opts Histogram [height=500 width=800 title="Alcohol Histogram by Wine Type" show_legend=True]
%%opts Histogram (alpha=0.6)

hist1 = hv.Histogram(np.histogram(wine_df[wine_df["Target"]=="Class_1"]['alcohol'], bins=30), kdims="alcohol", label="Class 1")
hist2 = hv.Histogram(np.histogram(wine_df[wine_df["Target"]=="Class_2"]['alcohol'], bins=30), kdims="alcohol", label="Class 2")
hist3 = hv.Histogram(np.histogram(wine_df[wine_df["Target"]=="Class_3"]['alcohol'], bins=30), kdims="alcohol", label="Class 3")

hist1 * hist2 * hist3

Getting Started with holoviews

5.9 Hexagonal Binning Plot (Hexbin Plot)

In this section, we have explained how to create a hexagonal binning plot commonly referred to as a hexbin plot using holoviews. We have created hexbin chart to show relationship between alcohol and malic acid. The Hexbin plot shows the count of samples that matches values of ingredients per each hex.

We have created a hexbin plot using HexTiles() method of holoviews. We have also included kernel density estimate using Bivariate() method.

%%opts HexTiles [width=550 height=500 title="Alcohol vs Malic Acid" colorbar=True]
%%opts HexTiles (cmap="OrRd")
%%opts Bivariate [show_legend=False]
%%opts Bivariate (cmap="OrRd")

hextiles = hv.HexTiles(data=wine_df, kdims=["alcohol", "malic_acid"])

bivariate = hv.Bivariate(data=wine_df, kdims=["alcohol", "malic_acid"])

hextiles * bivariate

Getting Started with holoviews

This ends our detailed tutorial explaining how to create charts using Python data visualization library Holoviews.

Want to Create Holoviews Chart from Pandas Dataframe with Just One Line Of Code?

We already saw above that how easy it is to create charts using holoviews.

But what if we can make it even easier?

Many of us use pandas dataframes for maintaining our tabular datasets. Pandas provide a simple plotting API to create charts through "plot()" method of dataframe. But charts created are static as it uses matplotlib as plotting backend.

What if we want to create interactive charts using same simple plotting API of pandas dataframe?

To our surprise, there is a library named hvplot that let us create interactive charts from pandas dataframe by calling plot() method. It uses holoviews as a backend to create charts.

Please feel free to check below link if you are interested in it.

References

Other Holoviews Tutorials

Other Python Data Visualization Libraries

Sunny Solanki  Sunny Solanki

YouTube Subscribe Comfortable Learning through Video Tutorials?

If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.

Need Help Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.


Subscribe to Our YouTube Channel

YouTube SubScribe

Newsletter Subscription