Plotly Python: Scatter Plots. A Deep Dive Into Scatter Plots with... | by Bryan White | Towards Data Science

In my last article on Plotly, we did a quick introduction to the library itself — covering the general structure of a graph object, using traces, and making customization's through the update_trace and update_layout functions.
Today we’re going to take a more intensive look at building and customizing scatter plots using the Plotly library.
For our dataset today, I have selected a Steam Games dataset from Kaggle, and I am interested in seeing if there is any relationship between the price of the game and the average playtime.
Loading into a dataframe, we can see the head as below:
Now, if you aren’t familiar with Steam you may not realize just how many games are on the platform. In the case of this dataset, if we do a count of the number of entries in the name column, we get 27075 titles.
However, since anyone can publish on Steam there are also a lot of outlier games that will affect our results — namely the amount of games with an average playtime of 0.If we run steamdf[steamdf[‘average_playtime’] == 0].count()we can see that there are 20905 games with no playtime!
Once I applied the criteria of:
steamdf = steamdf[(steamdf['average_playtime'] != 0) &          (steamdf['average_playtime'] < 40000)]  steamdf = steamdf[steamdf['price'] < 80]
I am left with 6160 games that we can look at.
So, let’s throw this into a quick scatter plot figure and see what the initial data looks like.
import plotly.graph_objects as gofig = go.Figure(data=go.Scatter(                x=steamdf['price'],                y=steamdf['average_playtime'],                mode='markers'))fig.show()
Pretty basic — but hey, we need to start somewhere, right?
Let’s go ahead and add a title and axis legends.While we’re at it, let’s style our markers a little. They look a little bland and blend in together.
import plotly.graph_objects as gofig = go.Figure(data=go.Scatter(                x=steamdf['price'],                y=steamdf['average_playtime'],                mode='markers',                marker_size=steamdf['ratio'],                marker=dict(                     color='rgb(255, 178, 102)',                     size=10,                     line=dict(                        color='DarkSlateGrey',                        width=1                      )               )))fig.update_layout(    title='Price vs. Average Playtime',    xaxis_title='Price (GBP)',    yaxis_title='Average Playtime (Minutes)')fig.show()
We start by using marker=dict() which then takes all the parameters that we use to style our markers (data points). There is an additional dict within marker that corresponds to the style options for the marker border.
Note how we color the markers themselves using an RGB value, whereas we color the marker outline with a CSS color code.Both are perfectly acceptable — you can even use RGBA to set the alpha.
The marker size is adjusted via the marker_size attribute. I created a new dataframe column ‘ratio’ where I did a scaled value of the positive_ratings / negative_ratings.A larger bubble means the game had a higher ratio of positive to negative ratings; we expect these games to generally have a higher average playtime.
Right now when we hover over the points, we only see the x and y values which isn’t exactly useful. However, it’s easy to add proper hover text to our points, so we can see the name of the game that we’re looking at.
By including the below code in our Figure object we can take the above hover data and turn it into something much better!
hovertext=steamdf['name'],hoverlabel=dict(namelength=0),hovertemplate='%{hovertext}<br>Price: %{x} <br>Avg. Playtime: %{y}'
It may look a little overwhelming, but lets break it down:-hovertext is a variable we are defining for use in our template-hoverlabel is mainly aesthetic in purpose. If you keep it in you may see the trace number off to the side of the tooltip box. I don’t like it, so this code will remove it.-hovertemplate allows you to create a template string to render whatever information you want to appear on the hoverbox.
Variables are added using the %{variable} format and you can make use of HTML tags such as <br>, <i>, <b>, etc.
You could spend countless hours playing around with all the style options that are available.If you feel you are lacking some inspiration, you could use the template property in fig.update_layout().
Example: fig.update_layout(template=’plotly_white’)
Options are: “plotly”, “plotly_white”, “plotly_dark”, “ggplot2”, “seaborn”, “simple_white”
However, I have whipped up something quickly to show you some of the most common customization’s you’ll want to do.
Namely, we have changed:- Axis grid/zero/plot border lines (color, width, and visibility)- Plot background and paper background colors- Title font, size, color- Custom ranging
fig = go.Figure(data=go.Scatter(                x=steamdf['price'],                y=steamdf['average_playtime'],                mode='markers',                marker_size=steamdf['ratio'],                hovertext=steamdf['name'],                hoverlabel=dict(namelength=0),                hovertemplate='%{hovertext}<br>Price: %{x:$}                              <br>Avg. Playtime: %{y:,} min',                marker=dict(                       color='rgb(255, 178, 102)',                       size=10,                       line=dict(                            color='DarkSlateGrey',                                   width=1                       )                )))fig.update_layout(    title='Price vs. Average Playtime',    xaxis_title='Price (GBP)',    yaxis_title='Average Playtime (Minutes)',    plot_bgcolor = 'white',    paper_bgcolor = 'whitesmoke',    font=dict(         family='Verdana',         size=16,         color='black'    ))fig.update_xaxes(showline=True,                 linewidth=2,                 linecolor='black',                 mirror=True,                 showgrid=False,                 zerolinecolor='black',                 zerolinewidth=1,                 range=[-1, 65])fig.update_yaxes(showline=True,                 linewidth=2,                 linecolor='black',                 mirror=True,                 showgrid=True,                 gridwidth=1,                 gridcolor='grey',                 zerolinecolor='black',                 zerolinewidth=1,                 range=[-2000, 40000])fig.show()
I hope this covers enough to get you feeling confident with creating and customizing scatter plots with Plotly!