The Plotly Python library is an interactive open-source library. This can be a very helpful tool for data visualization and understanding the data simply and easily. plotly graph objects are a high-level interface to plotly which are easy to use. It can plot various types of graphs and charts like scatter plots, line charts, bar charts, box plots, histograms, pie charts, etc.
So you all must be wondering why plotly over other visualization tools or libraries? Here’s the answer –
- Plotly has hover tool capabilities that allow us to detect any outliers or anomalies in a large number of data points.
- It is visually attractive that can be accepted by a wide range of audiences.
- It allows us for the endless customization of our graphs that makes our plot more meaningful and understandable for others.
Ok, enough theory let’s start.
Installation
plotly
may be installed using pip
:
$ pip install plotly==5.1.0
or conda
:
$ conda install -c plotly plotly=5.1.0
This package contains everything you need to write figures to standalone HTML files.
Note: No internet connection, account, or payment is required to use plotly.py. Prior to version 4, this library could operate in either an “online” or “offline” mode. The documentation tended to emphasize the online mode, where graphs get published to the Chart Studio web service. In version 4, all “online” functionality was removed from the
plotly
package and is now available as the separate, optional,chart-studio
package (See below). plotly.py version 4 is "offline" only, and does not include any functionality for uploading figures or data to cloud services.
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.write_html('first_figure.html', auto_open=True)
Plotly chart in Dash
Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash
, click "Download" to get the code and run python app.py
.
Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.
JupyterLab Support
For use in JupyterLab, install the jupyterlab
and ipywidgets
packages using pip
:
$ pip install “jupyterlab>=3” “ipywidgets>=7.6”
or conda
:
$ conda install “jupyterlab>=3” “ipywidgets>=7.6”
These packages contain everything you need to run JupyterLab…
$ jupyter lab
and display plotly figures inline using the plotly_mimetype
renderer...
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()
or using FigureWidget
objects.
import plotly.graph_objects as go
fig = go.FigureWidget(data=go.Bar(y=[2, 3, 1]))
fig
The instructions above apply to JupyterLab 3.x. For JupyterLab 2 or earlier, run the following commands to install the required JupyterLab extensions (note that this will require node
to be installed):
# JupyterLab 2.x renderer support jupyter labextension install jupyterlab-plotly@5.1.0 @jupyter-widgets/jupyterlab-manager
Please check out our Troubleshooting guide if you run into any problems with JupyterLab, particularly if you are using multiple python environments inside Jupyter.
See Displaying Figures in Python for more information on the renderers framework, and see Plotly FigureWidget Overview for more information on using FigureWidget
.
Jupyter Notebook Support
For use in the classic Jupyter Notebook, install the notebook
and ipywidgets
packages using pip
:
$ pip install “notebook>=5.3” “ipywidgets>=7.5”
or conda
:
$ conda install “notebook>=5.3” “ipywidgets>=7.5”
These packages contain everything you need to run a Jupyter notebook…
$ jupyter notebook
and display plotly figures inline using the notebook renderer…
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()
or using FigureWidget
objects.
import plotly.graph_objects as go
fig = go.FigureWidget(data=go.Bar(y=[2, 3, 1]))
fig
See Displaying Figures in Python for more information on the renderers framework, and see Plotly FigureWidget Overview for more information on using FigureWidget
.
Static Image Export
plotly.py supports static image export, using the either the kaleido
package (recommended, supported as of plotly
version 4.9) or the orca command line utility (legacy as of plotly
version 4.9).
Kaleido
The kaleido
package has no dependencies and can be installed using pip...
$ pip install -U kaleido
or conda.
$ conda install -c plotly python-kaleido
Orca
While Kaleido is now the recommended image export approach because it is easier to install and more widely compatible, static image export can also be supported by the legacy orca command line utility and the psutil
Python package.
These dependencies can both be installed using conda:
conda install -c plotly plotly-orca==1.3.1 psutil
Or, psutil
can be installed using pip...
pip install psutil
and orca can be installed according to the instructions in the orca README.
Extended Geo Support
Some plotly.py features rely on fairly large geographic shape files. The county choropleth figure factory is one such example. These shape files are distributed as a separate plotly-geo
package. This package can be installed using pip...
$ pip install plotly-geo==1.0.0
or conda.
$ conda install -c plotly plotly-geo=1.0.0
See USA County Choropleth Maps in Python for more information on the county choropleth figure factory.
Chart Studio Support
The chart-studio
package can be used to upload plotly figures to Plotly's Chart Studio Cloud or On-Prem services. This package can be installed using pip...
$ pip install chart-studio==1.1.0
or conda.
$ conda install -c plotly chart-studio=1.1.0
Note: This package is optional, and if it is not installed it is not possible for figures to be uploaded to the Chart Studio cloud service.
Where to next?
Once you’ve installed, you can use our documentation in three main ways:
- You jump right in to examples of how to make basic charts, statistical charts, scientific charts, financial charts, maps, and 3-dimensional charts.
- If you prefer to learn about the fundamentals of the library first, you can read about the structure of figures, how to create and update figures, how to display figures, how to theme figures with templates, how to export figures to various formats and about Plotly Express, the high-level API for doing all of the above.
- You can check out our exhaustive reference guides: the Python API reference or the Figure Reference
For information on using Python to build web applications containing plotly figures, see the Dash User Guide.
We also encourage you to join the Plotly Community Forum if you want help with anything related to plotly
.
What About Dash?
Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Everywhere in this page that you see fig.show()
, you can display the same figure in a Dash application by passing it to the figure
argument of the Graph
component from the built-in dash_core_components
package like this:
import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)
# fig.add_trace( ... )
# fig.update_layout( ... )import dash
import dash_core_components as dcc
import dash_html_components as htmlapp = dash.Dash()
app.layout = html.Div([
dcc.Graph(figure=fig)
])app.run_server(debug=True, use_reloader=False) # Turn off reloader if inside Jupyter
Plotly & Cufflinks
Plotly is an open-source and browser-based graphing library which facilitates interactive plotting. The library is available for a number of programming languages such as Python, R, MATLAB, Perl, Julia, Arduino, and REST, among others.
Cufflinks is another library that connects the Pandas data frame with Plotly enabling users to create visualizations directly from Pandas. The library binds the power of Plotly with the flexibility of Pandas for easy plotting.
Visualising Data With Plotly & Cufflinks
Installing Plotly and Cufflinks
To install Plotly and cufflinks type and execute the following commands
pip install plotly
pip install cufflinks
Note:
If you are using the Anaconda distribution make sure to activate your conda environment using the conda activate
command before executing the above commands. Use conda deactivate
to exit the conda environment.
Hands-On Visualisation
For those who have followed the Pandas plotting, this may sound fairly simple as all we need to do is import some libraries and rename the plot function of Pandas as iplot which stands for interactive plot. Let’s look at some examples.
Importing necessary libraries
For iplots, you might want to stick to using Jupyter Notebook as it has great support for it.
import plotly
import cufflinks as cf
import pandas as pd
import numpy as np
#Enabling the offline mode for interactive plotting locally
from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
init_notebook_mode(connected=True)
cf.go_offline()
#To display the plots
%matplotlib inline
Importing The Dataset
Consider a simple dataset of random numbers. You can either create your own download the same sample used in the below examples by clicking here.
data = pd.read_csv("sample_data.csv")
This is what the dataset looks like :
Creating Interactive Plots
Let’s do a simple plot of the numerical features in the dataset which are columns A, B and C.
data[['A','B','C']].iplot()
As you can see in the above image, Plotly provides a set of options to play around with the visualisation. On the top right corner of the generated plot, you can see 10 buttons that offer different functionalities. In the order of buttons from going left to right we have one to download the plot as a png image, toggle buttons to switch between zoom mode and pan mode, a zoom in and zoom out button, an autoscale button to reset the scale in the plot, a reset axis button, a button to toggle the spike lines in the graph, and pair of toggle button to switch between different mouse hover modes.
On the bottom right corner of the image, we also get an option to export the graph to Plotly’s online gallery.
Like the Pandas plot function, iplot enables users to use the ‘kind’ keyword argument to plot different kinds of plots such as scatter plots, bar plots, histograms etc. Let’s look at some examples.
Scatter plot :
data[['A','B','C']].iplot(kind = 'scatter' , mode = 'markers')
- kind = “scatter” specifies that we need a scatter plot.
- mode = “markers” sets the markers(Otherwise the plot will use lines by default).
You can also pass in the axis variables x and y as arguments, for example, x = ‘A’ sets column A along the X axis.
There is a wide range of arguments that can be passed to the iplot method to customise the visualisations. To understand the full list of arguments click here to head to the official documentation of Pyplot for Python,
Bar Graph:
data.iplot(kind = 'bar', x = 'D', y = 'C')
Surface Plots:
Plotly also allows users to plot 3D interactive plots.
data[['A','B','C']].iplot(kind = 'surface', colorscale = 'blues')
The above code displays the numerical features in the dataset along x,y and z-axis in a 3 Dimensional plane.
Outlook
That was a mere gentle introduction to Pyplot and its capabilities don’t stop here. With almost all sorts of customisations available for each kind of plot, there is no limit for creativity with Pyplot. Pyplot can interactively plot all kinds of charts that are available with Pandas plus many more beautiful visualisations.