Illustrate a Histogram with Median Line

First, we will load the packages of python that are used to make a histogram with a mean and median line using Altair. 

Python3




# import required modules
import altair as alt
import numpy as np
import pandas as pd


Now we will generate the data to make a histogram with the median line. Here, we will use Numpy to generate random numbers from a normal distribution and create panda data frames. 

Python3




# generating data
np.random.seed(42)
df = pd.DataFrame({'height': np.random.normal(150, 10, 1000)})


Basically here we tend to build the bar chart with the median line which can produce two layers of double star image object and combine them. Using Altair’s chart function, we create the base plot of the data frames of data. 

Python3




# initialize chart
base=alt.Chart(df)


Now we use Altair’s mark_bar() function and create the base object to make a histogram. Also, here we mention which variable we are interested to make a histogram. 

Python3




# generate histogram
hist = base.mark_bar().encode(
    x=alt.X('height:Q', bin=alt.BinParams(), axis=None), y='count()')


Using mark_rule() function in the Altair library, we use the base object with the data again to create a median line.

Python3




# generate median line
median_line = base.mark_rule().encode(
    x=alt.X('mean(height):Q', title='Height'), size=alt.value(5))


Now to form the fundamental histogram with the median line we have a tendency to merely combine the bar graph object and median line object as follows:

Python3




# depict illustration
hist+median_line


Output:

Therefore, here we get the histogram with the median line using Altair in python. 

Let us now understand to get the Customized histogram.

How To Make Histogram with Median Line using Altair in Python?

In this article, we will learn about how to make the histogram with the median line using Altair in python. This article is also a great example of Altair’s grammar of graphics. 

Altair is one of the latest interactive data visualizations library in python. Altair is based on vega and vegalite- A grammar of interactive graphics. Here we will use the import keyword to use Altair library for using it. 

Similar Reads

Illustrate a Histogram with Median Line

First, we will load the packages of python that are used to make a histogram with a mean and median line using Altair....

Customizing Histogram with Median Line using Altair

...