The way to improve your visualizations with matplotlib mosaic | by Gustavo Santos | Jun, 2023



Knowledge visualization is essential. We might develop lots simply from this sentence, however I consider you already bought the “image”. I’m positive this isn’t the primary time you hear this. And even whether it is, I nonetheless assume it’s not a shock, proper?

A plot is price a thousand observations.

If a picture is price a thousand phrases, I’d say that, for information science, a plot is price a thousand observations.

Anyway, let’s transfer to what’s necessary right here. The objective of this fast put up is to indicate you the tactic subplot_mosaic(). This perform is simply wonderful. Lately I used to be simply looking round and studying some Knowledge Science associated content material after I noticed it. I used to be simply amazed by how simple it turned to shortly create a number of plots in the identical determine.

Let’s see how it’s achieved within the subsequent part.

The information for use would be the dataset Suggestions, native from Seaborn package deal in Python.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Knowledge
df = sns.load_dataset('ideas')

Earlier than mosaic, there have been different methods to create subplots. They don’t seem to be tough in any respect, however they don’t seem to be as versatile because the subplot_mosaic() methodology. You may learn the subsequent put up to know what I’m speaking about.

The good contribution that the mosaic methodology offers us is the pliability to create many designs with little or no code. Have a look at the subsequent picture: if we need to reproduce that in matplotlib now, we are going to use the mosaic perform.

Discover that now we have 3 plots. Plot A will take one spot on the high left. Plot B will take one spot on the backside left of the determine. Plot C will take two spots at high and backside on the right-hand facet. Thus, now, all now we have to do is to translate that to Python, and also you’ll see it’s actually simple.

Mosaic to be created in matplotlib. Picture by the creator.

Let’s have a look at the code. We begin making a determine after which a mosaic variable. The mosaic variable can take lists or strings. I feel it’s simpler to make use of strings with triple quotes and “draw” with textual content precisely the way it will appear to be within the last plot determine. Discover that the usage of ac bc within the code is in the identical order and form because the earlier determine. By repeating c twice on the correct facet, I’m telling matplotlib that I need the plot C to take these two spots of the determine. The remainder of the code is simply common graphic creation code.

Should you have a look at the variable mosaic , you will note this: {‘a’: <Axes: label=’a’>, ‘c’: <Axes: label=’c’>, ‘b’: <Axes: label=’b’>}. So, it creates a dictionary, and we simply must level the place every graphic will go now.

# Plot with Mosaic
fig = plt.determine(structure= 'constrained')
mosaic = fig.subplot_mosaic('''

# Plot A
mosaic['a'].bar(df.intercourse, df.tip, coloration='coral')

# Plot B
mosaic['b'].scatter(df.total_bill, df.tip, coloration='forestgreen')

# Plot C
mosaic['c'].boxplot(df.tip, patch_artist=True);

Right here is the ensuing visualization.

Mosaic plot ensuing from the earlier code. Picture by the creator.

Okay. I hope I bought your consideration already.

We will create completely different layouts. Examine this out.

# Plot with Mosaic
fig = plt.determine(structure= 'constrained', figsize=(12,6))
mosaic = fig.subplot_mosaic('''

# Plot A
mosaic['a'].bar(, df.tip, coloration='coral')

# Plot B
mosaic['b'].boxplot(df.total_bill, patch_artist=True)

# Plot C
mosaic['c'].scatter(df.total_bill, df.tip, coloration='forestgreen');

Mosaic plot ensuing from the earlier code. Picture by the creator.

Or but, right here’s one other instance with extra graphics.

# Plot with Mosaic
fig = plt.determine(structure= 'constrained', figsize=(10,6))
mosaic = fig.subplot_mosaic('''

# Plot A
mosaic['a'].bar(, df.tip, coloration='coral')

# Plot B
mosaic['b'].boxplot(df.total_bill, patch_artist=True)

# Plot C
mosaic['c'].scatter(df.total_bill, df.tip, coloration='forestgreen')

# Plot D
mosaic['d'].scatter(df.tip, df.total_bill, coloration='purple')

# Plot E
mosaic['e'].scatter(df['size'], df.tip, coloration='gold');

Mosaic plot ensuing from the earlier code. Picture by the creator.

Setting Titles

However you is likely to be asking your self: what about chart titles?

Good query, I’d say! Let’s discover ways to place them.

The primary choice is the only: we are able to add a single title for the complete picture with one further line of code.

# Including a single title to the mosaic

plt.suptitle(''' -- P L O T S --
- Prime Left: Sum of ideas by Intercourse -
- Backside Left: Tip by Whole Invoice -
- Proper: Boxplot of Suggestions - ''')

Mosaic plot with a single title. Picture by the creator.

Alternatively, we could need to add one title per plot. Ergo, let’s create a loop that goes over every axes and every titles in a listing and match them one after the other. If we name mosaic.objects(), we are going to see that dictionary with tuples, identical to proven earlier than: (‘a’, <Axes: label=’a’>). To set the title, we need to entry the Axes portion — the second merchandise within the tuple — , and that’s why we use ax[1] within the code snippet within the sequence.

Right here is how it may be achieved.

# Outline Titles
titles = ['Sum of tips by Sex', 'Tip by Total Bill', 'Boxplot of Tips']

# One title per plot
for ax, g_title in zip(mosaic.objects(), titles):
ax[1].set_title(g_title, fontstyle='italic')

And that is the consequence.

Mosaic plot with a one title per plot. Picture by the creator.

Very good, isn’t it?

I consider plotting a number of graphics in a single determine will be useful for comparability, for presentation functions. And having a way that makes it simpler makes lots of distinction.

Bear in mind the steps

  1. Create a determine
  2. Create a mosaic variable with subplot_mosaic() and use ‘‘‘triple quotes’’’ to “draw” your mosaic. Write every graphic label as many instances as wanted to fill the spots within the mosaic.
  3. Add titles with plt.suptitle() or with a loop.

That’s all.

Should you preferred this content material, observe me for extra, right here.

Discover me on LinkedIn as nicely. And when you’re contemplating subscribing to Medium to learn my posts and rather more content material, think about using this referral code, as you inspire me to maintain creating content material.