首页 > 解决方案 > 如何堆叠多个图

问题描述

我有一个函数,它接受一个字典(键:字符串,值:二维数字)并在图表中显示字典的值(每个键一种颜色)。

我想直接用这个函数在同一个页面显示四个图,每个图对应一个特定的字典

如果可能的话,我想要一个像这样的脚本:

def my_function(dico):
    display picture

def global_function(multiple):
    plt.subplot(1,2,1)
    my_function(multiple[0])
    plt.subplot(1,2,2)
    my_function(multiple[1])

标签: pythonmatplotlib

解决方案


您可以将这些图绘制为一个图的子图。

import numpy as np
import matplotlib.pyplot as plt


#plotting function
def plot_2_subplots (x1, y1, x2, y2):
    f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
    ax1.plot(x1, y1)
    ax1.set_title('Plot 1')
    ax2.plot(x2, y2)
    ax2.set_title('Plot 2')

lists_a = sorted(d.items()) # return a list of tuples (sorted by key)
x1, y1 = zip(*lists_a) # unpack into tuple

lists_b = sorted(d.items()) # return a list of tuples (sorted by key)
x2, y2 = zip(*lists_b) # unpack into tuple

#Call plotting function
plot_2_subplots(x1, y1, x2, y2)

这会生成这个数字:在此处输入图像描述


推荐阅读