Interactive Visualizations with Plotly | by Soner Yıldırım | Towards Data Science

Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js). It allows to create interactive visualizations that can be displayed in Jupyter notebooks. It can be installed using pip or conda:
$ pip install plotly==4.8.0$ conda install -c plotly plotly=4.8.0
There are basically two ways to create figures with plotly.py:
Figures as dictionaries
Figures as graph objects
In this post, we will go through how to create many different kind of plots using graph objects. After installation, we can import graph objects:
import plotly.graph_objects as go
There are different ways to create graph object figures. One way is to use Figure constructor of graph objects. Let’s create a simple scatter plot:
import numpy as npa=np.random.random(10)b=np.random.randint(10, size=10)fig = go.Figure(data=go.Scatter(x=a, y=b, mode='markers'))fig.show()
We can also add additional traces on the same figure using add_trace:
fig = go.Figure(data=go.Scatter(x=np.arange(9), y=10*np.random.randn(10),mode='markers', name='markers'))fig.add_trace(go.Scatter(x=np.arange(9), y=np.random.randn(10),mode='lines+markers', name='lines+markers'))fig.show()
Another way to create figures is plotly express which is a high level API to produce graph object figures. We can import it with the following line of code:
import plotly.express as px
Let’s create a sample dataframe:
import pandas as pddf = pd.DataFrame({'col_a':np.random.random(10)*5,'col_b':np.random.randint(10, size=10),'col_c':[4.5, 4.7, 4.8, 3.4, 3.7, 4., 5.1, 3.2, 4.4, 3.3],'col_d':['a','a','b','a','a','b','b','c','c','c']})df
We can have an idea about the whole dataframe on one scatter plot:
fig = px.scatter(df, x="col_a", y="col_b", color="col_d", size='col_c')fig.show()
X axis represents “col_a” and y axis represents “col_b”. The size of the markers gives an idea about “col_c” whereas the color of markers represents the information in “col_d”. Thus, one scatter plot is able to tell us a lot about the dataset. Each dot (or marker) represent a row in the dataframe and we can hover on individual data points to see the values of all columns. This was a simple and random dataset. When we work with real datasets, the features of plotly interactive visulizations become more helpful.
Plotly contains the famous iris dataset that we can access with one line of code:
df_iris = px.data.iris()fig = px.scatter(df_iris, x="sepal_width", y="sepal_length", color="species",size='petal_length', hover_data=['petal_width'])fig.show()
The scatter plot above tells us how different species are grouped together as well as the variances within species.
It is also possible to represent different species in separate subplots. All we need to do is add facet_col or facet_row parameters. As the names suggest, facet_col creates subplots as columns and facet_row creates subplots as rows.
fig = px.scatter(df_iris, x="sepal_width", y="sepal_length", color="species", facet_col="species", title="Species Subplots")fig.show()
fig = px.scatter(df_iris, x="sepal_width", y="sepal_length", color="species", facet_row="species", title="Species Subplots")fig.show()
After a figure is rendered, we can update the layout using update_layout(). Consider the following figure:
We can update the font size of title with the following code:
fig.update_layout(title_text="Sample Dataset - Updated",                  title_font_size=20)
Another way to create subplots is to use make_subplots:
from plotly.subplots import make_subplotsfig = make_subplots(rows=1, cols=2)fig.add_scatter(y=np.random.random(10), mode="markers",                marker=dict(size=15, color="Blue"),                name="A", row=1, col=1)fig.add_bar(y=np.random.randint(10, size=10),            marker=dict(color="LightBlue"),            name="B", row=1, col=2)fig.show()
We specified the number of subplots and their positions using rows and cols parameters. Then we add the define the plots and specify the position. We can also specify the size and color of markers by passing a dictionary to marker parameter. The figure that is produced with the code segment above is:
We have covered some basic components of plotly.py library. Of course, this is just a little of what can be done with plotly. There are many other plot types that we can dynamically create with plotly. Its syntax is easy to understand as well. I will try to cover more complex plots in the upcoming posts. You can also check the plotly documentation which I think is well-documented with many different examples. Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills.
Thank you for reading. Please let me know if you have any feedback.