简体   繁体   English

在 matplotlib 中将 4 个不同的图组合在一起

[英]Combine 4 different plots together in matplotlib

I have 4 different functions to plot different type of plots.对于 plot 不同类型的绘图,我有 4 种不同的功能。 Now each function return a graph of size 20x10.现在每个 function 返回一个大小为 20x10 的图形。

def plot_func1(X,y):
    fig = plt.figure(figsize=(20,10))
    ax = sns.hist(X,y)
    plt.show()

def plot_func2(U,v):
    fig = plt.figure(figsize=(20,10))
    ax = plt.bar(U,v)
    plt.show()
def plot_func3():
def plot_func4():

How can I graph these 4 graph as subgraph?如何将这 4 个图绘制为子图? The idea is kinda like this这个想法有点像这样

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot_func1(x, y)

axs[0, 1].plot_func2(u, v)

axs[1, 0].plot_func3()

axs[1, 1].plot_func4()

You should create a function that takes an axis in parameter and plots onto it:您应该创建一个 function,它采用参数中的轴并在其上绘图:

def plot_func1(X, y, ax):
    ax.plot(X, y)

def plot_func2(U, v, ax):
    ax.bar(U, v)

Then in the main part, you define the figure and call the plotting functions:然后在主要部分中,定义图形并调用绘图函数:

f, ax = plt.subplots(1, 2, figsize=(20, 10))
plot_func1(X, y, ax[0])
plot_func2(U, v, ax[1])

Additionally, you can define this kind of function with a 'creating a new figure' as a default behavior.此外,您可以将这种 function 定义为“创建新图形”作为默认行为。 You can also pass additional arguments to the plot, ie to pass a color, a line width, or other matplotlib settings accepted by the plotting function used. You can also pass additional arguments to the plot, ie to pass a color, a line width, or other matplotlib settings accepted by the plotting function used.

def plot(x, y, ax=None, *args, **kwargs):
    if ax is None:
        f, ax = plt.subplots(1, 1, figisze=(10, 10))
    ax.plot(x, y, *args, **kwargs)

Personally, I would just include the **kwargs to avoid passing unwanted arguments to the plotting function.就个人而言,我只会包含**kwargs以避免将不需要的 arguments 传递给绘图 function。 I prefer an error to be raised in case a non-valid argument is passed.我更喜欢在传递无效参数的情况下引发错误。

EDIT: Full code编辑:完整代码

# -*- coding: utf-8 -*-

from matplotlib import pyplot as plt

def plot_func1(X, y, ax, *args, **kwargs):
    ax.plot(X, y, *args, **kwargs)
    
if __name__ == '__main__':
    f, ax = plt.subplots(1, 2, sharey=True, figsize=(3, 4))
    
    x1 = [1, 2, 3, 4]
    x2 = [1, 3, 7, 9]
    y = [1, 2, 3, 4]
    
    plot_func1(x1, y, ax[0])
    plot_func1(x2, y, ax[1], color='crimson')

Output: Output:

示例图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM