Introduction to the plotly Library in Python (Example & Tutorial)
In particular, plotly graphs provide interactive elements that enable users to modify, explore, and experience the visualized data in different ways.
This page shows an example of a plotly graph, demonstrates the main features of plotly, and outlines the situations when plotly may be the preferable solution.
You can scroll through their gallery to see a few examples.
Note: This article was created in collaboration with Kirby White. Kirby is a Statistics Globe author, innovation consultant, data science instructor. His Ph.D. is in Industrial-Organizational Psychology. You can read more about Kirby here!
Modules and Example Data
If you have not already done so, install and load these packages:
from vega_datasets import data import plotly.express as px
We’ll use the
stocks dataset for this example, which are included in the vega dataset.
df = data.iris() df
Let’s build and display a basic scatterplot that we’ll store in an object called
fig = px.scatter( data_frame = df, x = 'sepalWidth', y = 'sepalLength', color = 'species' ) fig.show()
It’s very simple to create a time series plot of stock prices, like this:
df2 = data.stocks() fig2 = px.line( data_frame = df2, x = 'date', y = 'price', color = 'symbol' ) fig2.show()
With another simple change, you can create a box plot to view the distribution of a dataset.
fig3 = px.box( data_frame = df2, x = 'symbol', y = 'price' ) fig3.show()
As you interact with your graph, you may have noticed that detailed information pops up over each point as you hover your cursor over it.
The plotly library provides a huge set of features. I’ve already shown you some of them. However, there are even more ways to visualize your data interactively!
Some of the most common features are:
- The tooltip “hover” info
- You can zoom in and out of plotly graphs
- It’s simple to export graphs as an image
Some of the more complex features include:
- The integration of multiple graphs together
- Hover info for templates
- Animated interactive graphs
- The integration of plotly graphics with enterprise coding environments
And there are many more!
You can check out these other articles to get started with plotly and for more detailed examples and videos:
- plotly Barplot in Python
- plotly Boxplot in Python
- plotly Histogram in Python
- plotly Line Plot in Python
- plotly Scatterplot in Python
- Introduction to the plotly Package in R
- Introduction to the Python Programming Language