Seaborn can do the job, then why Matplotlib? | by Mahbubul Alam | Towards Data Science

I had this thought a while back — is learning Matplotlib essential for beginners? Or can they get away with Seaborn? That thought came back recently while mentoring a cohort of data science students.
I know Matplotlib is a great library, it gives a lot of flexibility for customized data visualization.
But I also know it’s a complex library, especially for people who are new to data science and data visualization. It can be intimidating to some too!
In most data science curriculums Matplotlib and Seaborn are taught simultaneously, which, in my observation, creates quite a bit of confusion among people. They don’t understand why they needed both libraries if just one works. To alleviate this confusion I generally advise students to learn Seaborn first; and once they get comfortable with it, and understand its limitations, they will naturally realize the value of Matplotlib.
If the purpose of data visualization is to visualize distribution, trends and relationships of variables, Seaborn has all of these capabilities. All major statistical plots — distribution plot, boxplot, violin plot, scatter plot, barplot — can be created with Seaborn. For beginners, that’s all they need.
But then why Matplotlib?
Because Seaborn takes you just that far. Seaborn is a clear winner at the beginning due to its syntax simplicity and aesthetics. But with complexity, Matplotlib flexes its muscles.
The purpose of this article is to compare Seaborn and Matplotlib with a few basic figures and with minimal code. I’ll also show areas where Matplotlib shines and what makes it powerful in data visualization.
I am using the following dataset for the demo that comes with Seaborn:
import seaborn as snsdf = sns.load_dataset('tips')df.head()
As long as basic statistical plots are concerned, there is not much difference.
We can create a simple scatterplot for two variables total_bill and tips using Seaborn:
sns.scatterplot(x='total_bill', y = 'tip', data = df)
We can do the same using Matplotlib:
plt.scatter(x='total_bill', y = 'tip', data = df)
If you take a closer look you’ll probably see some minor differences already, but let’s ignore that for a moment.
Let’s try another plot, this time a boxplot.
sns.boxplot(y='total_bill', data = df)
And this is how it appears in Matplotlib:
plt.boxplot(x='total_bill', data = df)
In both cases, Seaborn and Matplotlib deliver similar statistical information, for example. But you probably realize the differences in plot quality and appearance.
Seaborn shines in two areas: 1) simplicity and 2) aesthetics.
By simplicity I mean its short, intuitive syntax to create plots. Let’s check out this example — the scatterplot above but with some added features.
First with Matplotlib:
color = {'Lunch': 'blue', 'Dinner': 'darkorange'}plt.scatter(x='total_bill', y='tip', data=df, c = df['time'].map(color))
Now with Seaborn:
sns.scatterplot(x='total_bill', y='tip', data=df, hue='time')
If you look at the codes, you’ll admit Seaborn is quite elegant and intuitive whereas Matplotlib’s codes are messy.
Now let’s turn to aesthetics. Granted, aesthetics is a subjective matter, but even then, you’ll appreciate the plot which looks better and aesthetically pleasing to you.
plt.violinplot(df['total_bill'])
sns.violinplot(y=df['total_bill']
If you compare the two violin plots created by two libraries, two things stand out:
Seaborn’s plot is aesthetically pleasing
Seaborn generates more information (do you see a boxplot inside the violin plot?)
Matplotlib is a massive library, with more than 70,000 lines of code I hear. People say it is a “low-level” library — meaning, it gives data scientists a lot of flexibility compared to the “high-level” one-liner Seaborn codes. Here are just a few examples of how Matplotlib powers up data visualization.
Matplotlib shines its best at subplots. You can create as many subplots as you want with plt.subplot(nrows, ncols)and put anything you want in each subplot. Below is a figure created with 4 empty subplots (nrows=2, ncols=2).
fig, ax = plt.subplots(2,2, figsize=(10,6))
We can now add Seaborn plots and place them wherever we want in the figure. Let’s utilize the 2nd and 4th subplots clockwise to place a boxplot and a scatterplot.
fig, ax = plt.subplots(2,2, figsize=(10,6))# boxplotsns.boxplot(y='tip', data=df, ax=ax[0,1])ax[0,1].set_title('This is Seaborn boxplot')# scatterplotsns.scatterplot(x='total_bill', y='tip', data=df, ax=ax[1,0])ax[1,0].set_title("This is Seaborn scatterplot")fig.tight_layout()
You can annotate your plots in a variety of ways —by adding texts, symbols, points, boxes, circles and much more. Here is an example — in the scatterplot below we want to indicate two data points as outliers.
plt.figure(figsize=(8,6))fig, ax = plt.subplots()sns.scatterplot(ax = ax, x=df['total_bill'], y = df['tip'])ax.annotate('Outlier', xy=(50, 10), xytext=(40, 9),            arrowprops=dict(facecolor='red'))ax.annotate('Outlier', xy=(7.5, 5.3), xytext=(10, 7),            arrowprops=dict(facecolor='red'))
You can take this idea in many directions and customize it in many different ways (e.g. annotating a time series plot to explain high points and low points).
Data scientists usually visualize data in two-dimensional plots. But Matplotlib also provides functionalities to create three-dimensional plots with its mplot3d toolkit. All you need to do is pass the keyword projection='3d' to an axis creation routine (e.g. add_subplot(projection=’3d’)). Here’s an example:
import matplotlib.pyplot as pltimport numpy as npn_radii = 8n_angles = 36radii = np.linspace(0.125, 1.0, n_radii)angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)[..., np.newaxis]x = np.append(0, (radii*np.cos(angles)).flatten())y = np.append(0, (radii*np.sin(angles)).flatten())z = np.sin(-x*y)ax = plt.figure(figsize=(14,8)).add_subplot(projection='3d')ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
All in all, Matplotlib helps create all kinds of custom plots of production quality. You can lay out your figure exactly the way you want, set the appropriate resolution and annotate figures as needed. To extend functionalities, there are several available toolkits such as Basemap, Cartopy, matplotlib2tikz, Qt, GTK etc. If you are interested in specific specialties of visualization there are plenty of resources and extensive documentation available online.
Seaborn is a high-level library. It provides simple codes to visualize complex statistical plots, which also happen to be aesthetically pleasing. But Seaborn was built on top of Matplotlib, meaning it can be further powered up with Matplotlib functionalities.
The original intent behind this article was to investigate whether you need to learn Matplotlib and Seaborn libraries as a beginner. You do not have to choose one or the other, you need both, but the question is do you need to learn them together at once?
To reiterate what I already said: learn Seaborn first, spend some time visualizing with it, understand its limitations. Seaborn’s limitations will naturally lead you into Matplotlib.
Hope it was a useful discussion, if you have comments feel free to write them down below or connect with me via Medium, Twitter or LinkedIn.