Scatter Plot – How to create Scatter plot in Plotly Python

Spread the love

In this post, you will learn how to create a scatter plot in plotly express and plotly graph objects.

1 . Create a scatter plot with plotly express –

Reading a dataset to work with.

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

url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/batting.csv"
df = pd.read_csv(url)
df.head()

To create a scatter plot using plotly express, we can use the px.scatter().

fig = px.scatter(df, x='SR', y='Runs')
fig.update_layout(title="Strike Rate VS Runs")
fig.show()

To visualize different groups in your data, you can use the color parameter.

fig = px.scatter(df, x='SR', y='Runs', color='Nationality')
fig.update_layout(title="Strike Rate VS Runs")
fig.show()

If you want you can also add marginal distribution in your plot.

fig = px.scatter(df, x='SR', y='Runs',color='Nationality', 
                 marginal_x='histogram', marginal_y='rug')
fig.update_layout(title="Strike Rate VS Runs")
fig.show()

px.scatter() also let’s you create facet plots. Facet plots are figures that are made up of multiple subplots which have the same set of axes, where each subplot shows a subset of the data.

fig = px.scatter(df, x='SR', y='Runs',color='Nationality', facet_col='Team', facet_col_wrap=3)
fig.update_layout(title="Strike Rate VS Runs")
fig.show()

You can also facet by rows along with facet_col, just set the facet_row parameter.

To add a regression or trend lines, use the trendline parameter. For this you have to install statsmodels library.

# install statsmodels library
pip install statsmodels
fig = px.scatter(df, x='SR', y='Runs', trendline="ols")
fig.update_layout(title="Strike Rate VS Runs")
fig.show()

2 . Create a Scatter plot with plotly graph objects –

To plot a scatter plot using plotly graph objects, you have to use go.Scatter()

fig = go.Figure()
fig.add_trace(go.Scatter(x= df['SR'], y=df['Runs'], mode='markers'))
fig.update_layout(title="Strike Rate VS Runs",
                 xaxis_title="Strike Rate",
                 yaxis_title="Runs")
fig.show()

1 . How to install plotly python with pip

2 . How to create a Line Chart with Plotly Python

3 . How to create a Bar Chart in Plotly Python

4 . How to create Horizontal Bar Chart in Plotly Python

5 . How to create a Histogram 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

Rating: 1 out of 5.

Leave a Reply