Plotly is a data plotting library with a clean interface designed to
allow you to build your own APIs.
![Colorful sound wave graph][1]
Plotly is a plotting ecosystem that allows you to make plots in [Python][2], as well as JavaScript and R. In this series of articles, I'm focusing on [plotting with Python libraries][3].
Plotly has three different Python APIs, giving you a choice of how to drive it:
* An [object-oriented API][4] that feels similar to Matplotlib
* A [data-driven API][5] that specifies plots by constructing dictionaries of JSON-like data
* A["Plotly Express" API][6] that gives you high-level plotting functions similar to Seaborn
I'll explore each of these APIs by making the same plot in each one: a grouped bar plot of historical UK election results.
### Making plots using Graph Objects
Plotly's object-oriented API is named graph_objects. It's somewhat similar to [Matplotlib's object-oriented API][7].
To create a multi-bar plot, you can construct a figure object containing four bar plots:
You can also specify your plot using basic Python data structures with the same structure as the object-oriented API. This corresponds directly to the JSON API for Plotly's JavaScript implementation.
This makes use of the data in [Long Form][12], also known as "tidy data." The columns are year, party, and seats, rather than being split by party. It's very similar to making a multi-bar plot in [Seaborn][13].
```
>> print(long)
year party seats
0 1922 Conservative 344
1 1923 Conservative 258
2 1924 Conservative 412
3 1929 Conservative 260
4 1931 Conservative 470
.. ... ... ...
103 2005 Others 30
104 2010 Others 29
105 2015 Others 80
106 2017 Others 59
107 2019 Others 72
[108 rows x 3 columns]
```
You can access the underlying Graph Objects API to make detailed tweaks. Add a title and a y-axis label:
This runs a temporary web server on an unused port and opens the default web browser to view the plot (the webserver is immediately torn down).
Unfortunately, the result is not perfect. The x-axis is treated as an integer, so the groups are far apart and small. This makes it quite difficult to see trends.
You might try to encourage Plotly Express to treat the x-values as strings by casting them to strings. You might expect this to result in them being plotted with even spacing and lexical ordering. Unfortunately, you still get them helpfully spaced numerically. Setting the xaxis_tickvals does not work as it did in graph_objects, either.
Unlike the similar example in [Seaborn][13], in this case, the abstraction does not appear to provide sufficient [escape hatches][15] to provide things exactly how you want them. But perhaps you could write your _own_ API?
### Building your own Plotly API
Not happy with how Plotly does something? Build your own Plotly API!
At its core, Plotly is a JavaScript library that makes plots using [D3][16] and [stack.gl][17]. The JavaScript library has an interface that consumes JSON structures that specify plots. So you just need to output JSON structures that the JavaScript library likes to consume.
Anvil did that to create a Python Plotly API that works entirely in the browser.
![Plotly uses a JavaScript library to create plots, driven by libraries in other languages via JSON][18]
In the Anvil version, you can use both the Graph Objects API and the Python data structure approach explained above. You run exactly the same commands, assigning the data and layout to a [Plot component][19] in your Anvil app.
Here's the multi-bar plot written in Anvil's client-side Python API:
The plotting logic is the same as above, but it's running _entirely in the web browser_—the plot is created by the Plotly JavaScript library on the user's machine! This is a big advantage over all the other [Python plotting libraries][3] in this series. All the other Python libraries need to run on a server.
Here's the interactive Plotly plot running in an Anvil app:
![The election plot on the web using Anvil's client-side-Python Plotly library][20]
You can [copy this example][22] as an Anvil app (Note: Anvil requires registration to use).
Running Plotly in the frontend has another advantage: it opens up many more options for customizing interactive behavior.
### Customizing interactivity in Plotly
Plotly plots aren't just dynamic; you can customize their interactive behavior. For example, you can customize the format of tool-tips using hovertemplate in each bar plot:
```
go.Bar(
x=x,
y=df['others'],
name='others',
marker=go.bar.Marker(color='#929591'),
hovertemplate='Seats: <b>%{y}</b>',
),
```
Here's what you get when you apply this to each bar plot:
This is useful, but it would be even better if you could execute any code you want when certain events happen—like when a user hovers over the bar and you want to display an information box about the relevant election. In Anvil's Plotly library, you can bind event handlers to events such as hover, which makes that sort of complex interactivity possible!
![A multi-bar plot with a hover event handler][24]
This is a rather extreme level of interactivity, and from the developer's point of view, an extreme level of customizability. It's all thanks to Plotly's architecture—Plotly has a clean interface that is explicitly designed to allow you to build your own APIs. It would be helpful to see this kind of great design everywhere!
### Custom interactivity using Bokeh
You've seen how Plotly uses JavaScript to create dynamic plots, and you can edit them live in the browser using Anvil's client-side Python code.
Bokeh is another Python plotting library that outputs an HTML document you can embed in a web app and get similar dynamic features to those provided by Plotly.(That's "BOE-kay," if you're wondering how to pronounce it.)
Enjoy customizing charts and share tips and tricks in the comments below.
* * *
_This article is based on [How to make plots using Plotly][9]on Anvil's blog and is reused with permission._
[18]: https://opensource.com/sites/default/files/uploads/plotly-arch.png (Plotly uses a JavaScript library to create plots, driven by libraries in other languages via JSON)
[20]: https://opensource.com/sites/default/files/uploads/plotting-in-anvil.gif (The election plot on the web using Anvil's client-side-Python Plotly library)