How to create a Histogram in plotly python

Spread the love

In this post, you will learn how to create a Histogram in python using plotly.

1 . How to Create a Histogram using Plotly Express –

Read a dataset to plot

import pandas as pd
import plotly.graph_objects as go
import as px

url = ""
df = pd.read_csv(url)

In statistics, a histogram is representation of the distribution of numerical data, where the data are binned and the count for each bin is represented. To create a histogram in plotly express, we use the px.histogram()

fig = px.histogram(df, x="Runs")

By default, the number of bins is chosen for you by plotly but you can also control it using the nbins parameter.

fig = px.histogram(df, x="Runs", nbins=20)

You can also plot categorical data using px.histogram()

fig = px.histogram(df, x="Team")

By default, plotly shows the count of samples in each bin. With the histnorm argument, it is also possible to represent the percentage or fraction of samples in each bin, (histnorm=’percent’ or ‘probability’) or a density histogram (the sum of all bar areas equals the total number of sample points, density), or a probability density histogram (the sum of all bar areas equals 1, probability density)

fig = px.histogram(df, x="Runs", histnorm='percent')

To change the colors of the histogram bar, use the color_discrete_sequence parameter

fig = px.histogram(df, x="Runs", 

You can also use the color parameter to compare the distribution of different groups.

fig = px.histogram(df, x="Runs", color='Nationality')

With the text_auto parameter, you can also add text to the histogram bars.

fig = px.histogram(df, x="Runs", nbins=20, text_auto=True)

2 . How to create histogram with plotly graph objects –

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Histogram(x = df['Runs']))
fig.update_layout(xaxis_title="Runs", yaxis_title="Count")

Normalized Histogram

fig = go.Figure()
fig.add_trace(go.Histogram(x = df['Runs'], histnorm='percent'))
fig.update_layout(xaxis_title="Runs", yaxis_title="percent")

Overlay histogram –

# groups 
indian = df[df['Nationality']=='Indian']
overseas = df[df['Nationality']=='Overseas']

fig = go.Figure()
fig.add_trace(go.Histogram(x = indian['Runs'], name='Indian'))
fig.add_trace(go.Histogram(x = overseas['Runs'], name='Overseas'))

1 . How to install plotly python with pip

2 . How to create a Line Chart with Plotly Python

3 . How to create Scatter plot in Plotly Python

4 . How to create a Bar Chart in Plotly Python

5 . How to create Horizontal Bar Chart in Plotly Python

6 . How to Create a Box Plot in Plotly Python

7 . How to create a Pie Chart in Plotly Python

8 . How to create a Dot Plot in Plotly Python

9 . How to Create Heatmap with Plotly Python

10 . How to Create a Violin Plot in Plotly Python

11 . How to Create Subplots in Plotly Python

Leave a Reply