# How to create a Histogram in plotly python

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 plotly.express as px

df.head()

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")
fig.show()

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)
fig.show()

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

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

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')
fig.show()

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

fig = px.histogram(df, x="Runs",
histnorm='percent',
color_discrete_sequence=['seagreen'])
fig.show()

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

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

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)
fig.show()

## 2 . How to create histogram with plotly graph objects –

import plotly.graph_objects as go

fig = go.Figure()
fig.update_layout(xaxis_title="Runs", yaxis_title="Count")
fig.show()

Normalized Histogram

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

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'))
fig.update_layout(barmode="overlay")
fig.update_traces(opacity=0.7)
fig.show()