
In this post, you will learn How to create a Box Plot in Plotly Python.
1 . Create a Box Plot using Plotly Express –
Read a dataset to work with.
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/batting.csv"
df = pd.read_csv(url)
df.head()

To create a Box plot in Plotly express, we use the px.box() method.
fig = px.box(df, y="Runs")
fig.show()

If a column name is given as x argument, a box plot is drawn for each value of x.
fig = px.box(df, x="Team", y="Runs")
fig.show()

You can also use the color parameter to further segments the data.
fig = px.box(df, x="Team", y="Runs", color="Nationality")
fig.show()

If you want You can also show the underlying data using the points parameter. By default it shows the outliers but you can also show all the data by setting points=’all’
fig = px.box(df, x="Nationality", y="Runs", points="all")
fig.show()

You can also create styled box plot
fig = px.box(df, x="Nationality", y="Runs", notched=True)
fig.show()

2 . Create a Box Plot with plotly graph objects –
To create a box plot with plotly graph objects, we use the go.Box() method.
fig =go.Figure()
fig.add_trace(go.Box(y= df['Runs']))
fig.update_layout(yaxis_title="Runs")
fig.show()

Multiple box plot –
indian = df[df['Nationality']=="Indian"]
overseas = df[df['Nationality']=="Overseas"]
fig =go.Figure()
fig.add_trace(go.Box(y=indian['Runs'], name="Indian"))
fig.add_trace(go.Box(y=overseas['Runs'], name="Overseas"))
fig.update_layout(xaxis_title="Nationality", yaxis_title="Runs")
fig.show()

Horizontal Box Plot –
indian = df[df['Nationality']=="Indian"]
overseas = df[df['Nationality']=="Overseas"]
fig =go.Figure()
fig.add_trace(go.Box(x=indian['Runs'], name="Indian"))
fig.add_trace(go.Box(x=overseas['Runs'], name="Overseas"))
fig.update_layout(xaxis_title="runs", yaxis_title="Nationality")
fig.show()

Colored Box Plot –
indian = df[df['Nationality']=="Indian"]
overseas = df[df['Nationality']=="Overseas"]
fig =go.Figure()
fig.add_trace(go.Box(x=indian['Runs'], name="Indian", marker_color="seagreen"))
fig.add_trace(go.Box(x=overseas['Runs'], name="Overseas", marker_color="red"))
fig.update_layout(xaxis_title="runs", yaxis_title="Nationality")
fig.show()

Related Posts –
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 Histogram 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