简体   繁体   English

matplotlib:在函数中绘制图形,然后将每个图形添加到单个子图形图形中

[英]matplotlib: make plots in functions and then add each to a single subplot figure

I haven't been able to find a solution to this.. Say I define some plotting function so that I don't have to copy-paste tons of code every time I make similar plots... 我无法找到解决方案。假设我定义了一些绘图功能,这样我每次制作相似的图时都不需要复制大量的代码...

What I'd like to do is use this function to create a few different plots individually and then put them together as subplots into one figure. 我想做的是使用这个函数分别创建几个不同的图,然后将它们作为子图放在一起。 Is this even possible? 这甚至可能吗? I've tried the following but it just returns blanks: 我尝试了以下但它只返回空白:

import numpy as np
import matplotlib.pyplot as plt

# function to make boxplots
def make_boxplots(box_data):

    fig, ax = plt.subplots()

    box = ax.boxplot(box_data)

    #plt.show()

    return ax

# make some data:
data_1 = np.random.normal(0,1,500)
data_2 = np.random.normal(0,1.1,500)

# plot it
box1 = make_boxplots(box_data=data_1)
box2 = make_boxplots(box_data=data_2)

plt.close('all')

fig, ax = plt.subplots(2)

ax[0] = box1
ax[1] = box2

plt.show()

I tend to use the following template 我倾向于使用以下模板

def plot_something(data, ax=None, **kwargs):
    ax = ax or plt.gca()
    # Do some cool data transformations...
    return ax.boxplot(data, **kwargs)

Then you can experiment with your plotting function by simply calling plot_something(my_data) and you can specify which axes to use like so. 然后你可以通过简单地调用plot_something(my_data)来试验你的绘图功能,你可以像这样指定使用哪些轴。

fig, (ax1, ax2) = plt.subplots(2)
plot_something(data1, ax1, color='blue')
plot_something(data2, ax2, color='red')

Adding the kwargs allows you to pass in arbitrary parameters to the plotting function such as labels, line styles, or colours. 添加kwargs允许您将任意参数传递给绘图功能,例如标签,线条样式或颜色。

The line ax = ax or plt.gca() uses the axes you have specified or gets the current axes from matplotlib (which may be new axes if you haven't created any yet). 线ax = ax or plt.gca()使用您指定的轴或从matplotlib获取当前轴(如果您尚未创建任何轴,则可能是新轴)。

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

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