Plotting in Seaborn is much simpler than in Matplotlib. While Matplotlib makes the hard things possible, Seaborn makes complicated things uncomplicated by giving you a range of plot types that "just work."
A one-liner… almost
In this series, I'm comparing Python plotting libraries by making the same plot in each one. It's a multi-group bar plot of UK election results.
Before we go further, note that you may need to tune your Python environment to get this code to run, including the following.
- Running a recent version of Python (instructions for Linux, Mac, and Windows)
- Verify you're running a version of Python that works with these libraries
The data is available online and can be imported using pandas:
import pandas as pd
df = pd.read_csv('https://anvil.works/blog/img/plotting-in-python/uk-election-results.csv')
Here's how to create this multi-group bar plot in Seaborn:
ax = sns.barplot(
data=df,
x="year",
y="seats",
hue="party",
palette=['blue', 'red', 'yellow', 'grey'],
saturation=0.6,
)
The result:
Seaborn has such a simple interface because it doesn't require you to manipulate your data structure in order to define how your plot looks. Instead, you get your data into Long Form, and then your data manipulation is done. All you need to do is tell Seaborn which aspects of the plot to map to which variables in your data.
If you want to encode the party
variable in the hue
of the bars, specify:
hue="party"
and if you want to encode the year
variable as position on the X-axis, specify:
x="year"
The way that Seaborn deals with colors is really interesting. You can specify colors using human-readable color names. I used red, blue, yellow, and grey, but you can also use colors like ugly green, dull blue, and electric purple. These are mapped to a crowdsourced library of color-name definitions created by XKCD author Randall Munroe.
For completeness, I must mention that there are a couple of lines of boilerplate to run before the plot statement:
# A couple of lines of boilerplate
sns.set()
plt.figure()
You have to import the library and your data, of course:
# Import Matplotlib and Seaborn
import matplotlib.pyplot as plt
import seaborn as sns
And since this is a wrapper around Matplotlib, you still need to cast the Matplotlib plotting spell at the end:
plt.show()
No compromise
OK, so I have this really beautiful interface that makes common plots really simple. But doesn't that take away my power? Luckily, that's not the case. Seaborn is the good kind of abstraction—it makes the common cases ridiculously easy, but it also gives you access to lower levels of abstraction. Just like Anvil, Seaborn gives you "escape hatches" to use the underlying layers when you need them.
When I called sns.barplot
, it returned the Matplotlib Axis
object for that plot. I can use this to add a title and grid and tweak the axis labels, just as I did in Matplotlib:
ax.set_title('UK election results')
ax.grid(color='#cccccc')
ax.set_ylabel('Seats')
ax.set_xlabel(None)
ax.set_xticklabels(df["year"].unique().astype(str), rotation='vertical')
Here's the result:
You can copy this example as an Anvil app here (Note: Anvil requires registration to use).
Next: Dynamic plots in client-side Python
Seaborn is one of my favorite plotting libraries, thanks to this combination of simplicity and power. But it produces static images, and if you're using them on the web, you might want a little more interactivity.
Next time, I'll look at Plotly, which allows you to create dynamic plots in the browser, with a Python interface over a JavaScript core.
This article is based on How to make plots using Seaborn on Anvil's blog and is reused with permission.
Comments are closed.