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()
推荐答案
我倾向于使用以下模板
def plot_something(data, ax=None, **kwargs):
ax = ax or plt.gca()
# Do some cool data transformations...
return ax.boxplot(data, **kwargs)
然后您可以通过简单地调用 plot_something(my_data)
来试验您的绘图功能,并且您可以像这样指定要使用的轴.
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.
fig, (ax1, ax2) = plt.subplots(2)
plot_something(data1, ax1, color='blue')
plot_something(data2, ax2, color='red')
添加 kwargs
允许您将任意参数传递给绘图功能,例如标签,线条样式或颜色.
Adding the kwargs
allows you to pass in arbitrary parameters to the plotting function such as labels, line styles, or colours.
ax = ax或plt.gca()
行使用您指定的轴或从matplotlib获取当前轴(如果尚未创建,则可能是新轴).
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).
这篇关于matplotlib:在函数中绘制图,然后将每个图添加到单个子图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!