Data Visualization Using Bqplot in Python
Bqplot is a powerful and flexible tool for creating interactive visualizations within Jupyter Notebooks. Its integration with ipywidgets and use of D3.js make it a valuable library for data scientists and developers who need to build interactive data visualization applications.
What is BqPlot in Python?
BqPlot is a fun tool that helps you make cool visualizations in Jupyter using Python. You can make the visualizations interactive and add them to other widgets to make them awesome without needing to know any other coding languages. Bqplot integrates seamlessly with the Jupyter Notebook environment, leveraging the ipywidgets library to create rich, interactive plots that can be dynamically updated based on user interactions or real-time data.
Features of BqPlot
- BqPlot supports core plotting, meaning it provides a set of essential plotting tools and functions.
- BqPlot is very responsive, powered by the same machinery that powers Jupiter's widgets.
- BqPlot has Selectors. They enable selecting slices of data.
- 1D Selector: This selects data along one dimension (x or y).
- 2D Selector: Using rectangular brushing, this selects data along two dimensions (x and y).
- Lasso: Similar to 2D Selector, lasso selects data along two dimensions but using a lasso tool.
- By integrating BqPlot with the Jupiter widget library, we can build interactive dashboards.
Required Installation and Import
pip install bqplot
>>> import bqplot as bq
Line Plot using BqPlot
Following are the few features Line Mark provides:
- We can plot single or multiple arrays of y-values with a single or multiple arrays of x-values.
- We can style the plotting line with different styles by using different attributes like line_style, colour, markers, stroke_width etc.
- We can create area charts by filling colours in between or below the lines.
- We can specify markers at each point passed to the line.
Now let's execute a code to build a line plot.
First let's import all the libraries, Now to build the line plot, First, we will define the x-axis data using the pd.date_range() function, which generates a range of dates starting from January 1, 2022, with a total of 100 periods. Next, for y-axis we will create a cumulative sum of random numbers using np.random.randn().cumsum() function.
Finally, after scaling the x-axis, we will use plt.plot() function to build the line plot by providing all the required parameters.
import bqplot as bq
import pandas as pd
import bqplot.pyplot as plt
import numpy as np
x = pd.date_range(start="2022-01-01", periods=100)
y = np.random.randn(100).cumsum()
fig = plt.figure(title="Time Series")
plt.scales(scales={"x": bq.DateScale()})
time_series_line = plt.plot(x, y, "green", stroke_width=1,
fill="bottom",
fill_colors=["green"],
fill_opacities=[.4])
fig
OUTPUT:

Pie Plot using BqPlot
A pie plot is a circular graphic that is divided into many slices based on numerical proportions. We will use the pie() function from the bqplot.pyplot to create the pie chart. First, we will create 3 random numbers using np.random function and store them in the data variable. Then we will create the figure object 'fig' using which we keep the duration of the animation to 1000 milliseconds or 1 second. Finally, we will call the pie() function in which we will pass the data and the labels. In this way, we can create a simple pie plot.
import numpy as np
import bqplot.pyplot as plt
import string
data = np.random.rand(3)
fig = plt.figure(animation_duration=1000)
pie = plt.pie(data, display_labels="outside", labels=list(string.ascii_uppercase))
fig
OUTPUT:

Bar Plot using BqPlot
In a bar plot the data is represented using horizontal or vertical bars showing the magnitude of different categories. Unlike pie plot, here we have to define both x-axis and y-axis data. In x-axis we have to keep categorical data in a list form and in y-axis we have to keep numerical values. In this example, for x-axis we will keep first 5 alphabets as categorical data using list() function, and for y-axis we will use np.random function to generate 5 random numbers. Finally we will call bar() function in which we pass both x-axis and y-axis data. In this way we can create a simple bar plot using bqplot.
import bqplot.pyplot as plt
import numpy as np
fig = plt.figure(title="Bar Chart")
x = list("ABCDE")
y = np.random.rand(5)
bar = plt.bar(x, y)
fig
OUTPUT:

Box Plot using BqPlot
A box plot is a statistical way of displaying the distribution of data. It is also known as box-and-whisker plot. It displays data based on five-number summary: first quartile, median, third quartile, minimum and maximum.
In this example, we will build 4 different box plots in one chart. For this, in x-axis we create a list of 4 values or names for 4 box plots, and in y-axis we create a numerical values in different lists for different plots. After scaling, we will call the Boxplot() function of bqplot, in which we will pass the data and the colours we want.
import numpy as np
from bqplot import LinearScale, Axis, Boxplot, Figure
# Data for the box plot
x_data = [1, 2, 3, 4]
y_data = [[188.67, 186.91, 187.17, 189.83, 189.64, 190.06, 189.01, 192.31, 191.62, 193.11, 194.00, 193.75, 192.80, 192.96, 191.81, 191.28, 191.72, 191.20, 190.68],
[191.95, 191.56, 192.30, 192.00, 192.25, 192.99, 191.16, 190.41, 191.23, 190.10, 190.07, 189.36, 187.38, 187.88, 191.81, 191.28, 191.72, 189.99, 190.14],
[187.95, 187.34, 187.47, 186.63, 184.30, 185.97, 187.10, 189.64, 189.15, 191.67, 194.00, 194.57, 195.78, 194.40, 195.24, 193.63, 190.85, 192.5, 192.49],
[192.36, 188.49, 189.86, 188.00, 187.70, 188.42, 187.22, 188.04, 188.53, 188.39, 186.35, 181.27, 181.71, 180.37, 180.72, 180.88, 182.14, 181.55, 182.82]
]
# Scales and Axes
sc_x, sc_y = LinearScale(), LinearScale()
ax_x, ax_y = Axis(label="X", scale=sc_x), Axis(label="Y", scale=sc_y, orientation="vertical")
# Boxplot
boxes = Boxplot(
x=x_data, y=y_data, scales={"x": sc_x, "y": sc_y},
box_fill_color="blue", outlier_fill_color="red", stroke="red",
opacities=[0.1, 0.2], box_width=10
)
# Figure
fig = Figure(axes=[ax_x, ax_y], marks=[boxes])
fig
OUTPUT:

Heat Plot using BqPlot
Heatmaps are plots in which the data is represented in a matrix form and it helps us understand the data using a spectrum of colours. One of the main usage of heatmaps in the phase of exploratory data analysis is to understand the correlation between variables of the dataset.
To plot a heatmap using bqplot, we need to use gridheatmap() function of bqplot. Like barplot we need to specify x-axis and y-axis data, but unlike barplot the categorical data will be on the y-axis in heatmap.
import bqplot as bq
fig = plt.figure(title='Heatmap', padding_y=0)
data = np.random.randn(10, 10)
row = list("ABCDEFGHIJ")
column = np.arange(10)
grid_map = plt.gridheatmap(
color=data,
row=row,
column=column,
display_format=".2f",
font_style={"font-size": "16px", "fill": "black", "font-weight": "bold"},
scales={"color": bq.ColorScale(scheme="Greens")}
)
fig
OUTPUT:

Area Charts using BqPlot
We can create area charts from line charts by using different attributes like:
- fill
- fill_color
- fill_opacities
First, we will create a list of 100 numbers that go up by the same amount each time. Next, we are going to make up some numbers for four different lines on a graph: line 1, line 2, line 3, and line 4. We will add up some random numbers and start with a total of 10.
Then, we will keep adding more random numbers to the total for each point. We will do this three more times, each time adding a different random number between 0 and 5.
Finally, we will make a chart called "Stacked Area Chart" using plt.figure(). We will create a stacked area chart by using plt.plot() and giving it the x-axis information and a list of four different sets of information for the y-axis.
We will make the lines disappear by setting the stroke_width to 0, and we will color in the area between the lines by setting the fill to "between".
fig = plt.figure(title="Stacked Area Chart")
x = np.arange(100)
y1 = np.random.randn(100).cumsum() + 10
y2 = y1 + np.random.rand(100) * 5
y3 = y2 + np.random.rand(100) * 5
y4 = y3 + np.random.rand(100) * 5
lines = plt.plot(x, [y1, y2, y3, y4], stroke_width=0,
fill="between",
fill_opacities=[.8] * 4)
fig
OUTPUT:

Scatter Plot using BqPlot
The Scatter mark helps you see where things are on a map. This is a chart that shows different points in multiple ways, like their position, color, and size. You can choose different shapes for the points. You can also change the points by clicking on them or moving them around.
First, we will create a set of 20 random numbers for both the x and y axes by calling np.random.rand(2, 20).
After that, we will make a picture using plt.figure(). We will create a little box that shows the exact numbers for each point on a graph, with two numbers after the decimal point.
Last, we will make a scatter plot by using plt.scatter(). We will tell it where to put the points on the x and y axes, what color the points should be (green), what color the borders of the points should be (black), and what information should pop up when you hover over the points.
fig = plt.figure()
x, y = np.random.rand(2, 20)
tooltip = bq.Tooltip(fields=["x", "y"], formats=[".2f", ".2f"])
scatter = plt.scatter(x, y, colors=["green"], stroke="black",
tooltip=tooltip)
fig
OUTPUT:

Map using BqPlot
The Map mark helps us make maps by choosing different ways to show the Earth's surface. We can use colors to show different things on the map, like population or temperature. We can also make the map interactive by adding things like pop-up information or selecting areas on the map.
Choropleth
First, we will make a plot called "Choropleth" and give it the title "Choropleth" using plt.figure() function. Next, we will choose different shades of green to show different numbers on the map. We will use a tool called "plt.geo()" and choose a map called "WorldMap" to use. We will also pick colors for certain areas on the map. If we don't pick a color for a certain area, it will have a default color.
fig = plt.figure(title="Choropleth")
plt.scales(scales={"color": bq.ColorScale(scheme="Greens")})
chloro_map = plt.geo(
map_data="WorldMap",
color={643: 105, 4: 21, 398: 23, 156: 42, 124: 78, 76: 98},
colors={"default_color": "Grey"},
)
fig
OUTPUT:

Advanced Projection
Now, we will make a special plot called "Advanced Projection" by using plt.figure() and giving it the title "Advanced World Map". Next, we will decide how big the map should be and where it should focus. We are using a tool called bq.Orthographic() to do this. We are setting the size to 375, the center to [0, 25], and the rotation to (-50, 0). This will help us show the map in a certain way. Next, we will use the geographic scale on the projection with plt.scales(scales={"projection": geo_scale}). Next, we will make a cool map of the world using plt.geo(). We will use a data source called "WorldMap" and give different colors to different parts of the map. If we don't give a specific color to a region, it will have a default color.
fig = plt.figure(title="Advanced World Map")
geo_scale = bq.Orthographic(scale_factor=375, center=[0, 25], rotate=(-50, 0))
plt.scales(scales={"projection": geo_scale})
map_mark = plt.geo(
map_data="WorldMap",
colors={682: 105, 356:42, 643: 78, "default_color": "grey"},
)
fig
OUTPUT:
