[Python] Draw multiple subgraphs more elegantly in the same graph

1 Introduction

Data visualization is very important. There is a saying called 一图顶千言, I believe many friends should have heard of this sentence; even if someone hears it for the first time, I think they should agree, which is enough to illustrate the importance of data visualization. In our previous blog, we introduced how to subplotdraw multiple subgraphs in a subgraph by using . Recently, I discovered a more elegant implementation, and I can’t wait to share it with you.

Without further ado, let's get started!

2. Take a chestnut

In order to more conveniently draw multiple subgraphs in the image in Figure 1, here I emphasize the Amway subplot_mosaic()function, which makes the layout of the subgraphs more flexible. Let's look directly at the following example:
insert image description here

Note that at this point we have 3 subplots. Diagram A will occupy a position in the upper left corner; diagram B will occupy a position in the lower left corner of the diagram; while diagram C will occupy two positions in the top and bottom right corners of the diagram. Now, all we have to do is convert it to a Python implementation, and you'll find it's pretty easy.

3. Code implementation

We use matplotlibthe functions in the library subplot_mosaicto achieve the above functions, the code is as follows:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Data
df = sns.load_dataset('tips')
# Plot with Mosaic
fig = plt.figure(layout= 'constrained')
mosaic = fig.subplot_mosaic('''
                            ac
                            bc
                            ''')

# Plot A
mosaic['a'].bar(df.sex, df.tip, color='coral')
# Plot B
mosaic['b'].scatter(df.total_bill, df.tip, color='forestgreen')
# Plot C
mosaic['c'].boxplot(df.tip, patch_artist=True);

The result of the operation is as follows:
insert image description here

4. Code Analysis

Let's take a closer look at the above code, we start by creating a figure, and then create a mosaicvariable, where subplot_mosaicthe input parameter of the function is a string. Note that ac bcthe order and shapes used in the code are the same as in the image above. cTell matplotlibus that we want the plot cto occupy two positions in the graph by repeating it twice on the right side . The rest of the code is just regular single subplot creation code.

We can print mosaic the value of the variable, as follows:
{'a': <Axes: label='a'>, 'c': <Axes: label='c'>, 'b': <Axes: label='b'>}.
Therefore, in essence, we call subplot_mosaicthe function to return a dictionary, and the rest is to routinely draw the submap at each corresponding position.

5. Change the layout

If you understand the above code, then we can easily change the layout of the above subgraph.
code show as below:

# Plot with Mosaic
fig = plt.figure(layout= 'constrained', figsize=(12,6))
mosaic = fig.subplot_mosaic('''
                            aaa
                            bcc
                            ''')

# Plot A
mosaic['a'].bar(df.day, df.tip, color='coral')
# Plot B
mosaic['b'].boxplot(df.total_bill, patch_artist=True)
# Plot C
mosaic['c'].scatter(df.total_bill, df.tip, color='forestgreen');

The result is as follows:
insert image description here

6. Add a title

If we need to add a title to the above chart, how to achieve it? Essentially we can add a title to the entire image with one extra line of code.

# Adding a single title to the mosaic

plt.suptitle('''        -- P L O T S --
                - Top Left: Sum of tips by Sex -
                - Bottom Left: Tip by Total Bill -
                - Right: Boxplot of Tips - ''')

The result is as follows:
insert image description here
what? You want to add a title to each subplot. Since mosaicit is a dictionary, we can create a loop to key-valueachieve it by traversing what we want. code show as below:

# Define 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.items(), titles):
    ax[1].set_title(g_title, fontstyle='italic')

The result is as follows:
insert image description here

Wow, after step-by-step beautification, the final result really looks much better.

7. Summary

I believe that drawing multiple graphs in a single graph is helpful for comparison and visualization purposes, and having a cleaner way of making it would improve a lot, and I recommend it.

Are you useless?

Guess you like

Origin blog.csdn.net/sgzqc/article/details/131274740