简体   繁体   English

如何在子图中绘制图形(Matplotlib)

[英]How to plot figures in subplots (Matplotlib)

I understand there are various ways to plot multiple graphs in one figure. 我知道有多种方法可以在一个图中绘制多个图形。 One such way is using axes, eg 一种这样的方式是使用轴,例如

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([range(8)])
ax.plot(...)

Since I have a function that beautifies my graphs and subsequently returns a figure, I would like to use that figure to be plotted in my subplots. 由于我有一个美化我的图形并随后返回一个图形的函数,因此我想使用该图形在子图中绘制。 It should look similar to this: 它看起来应该类似于:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(figure1) # where figure is a plt.figure object
ax.plot(figure2)

This does not work but how can I make it work? 这不起作用,但是我如何使其起作用? Is there a way to put figures inside subplots or a workaround to plot multiple figures in one overall figure? 有没有办法将图形放置在子图中,或者有一种变通方法来在一个整体图形中绘制多个图形?

Any help on this is much appreciated. 任何帮助对此表示感谢。 Thanks in advance for your comments. 预先感谢您的评论。

If the goal is just to customize individual subplots, why not change your function to change the current figure on the fly rather than return a figure. 如果目标只是自定义单个子图,为什么不更改功能以动态更改当前图形而不是返回图形。 From matplotlib and seaborn , can you just change the plot settings as they are being plotted? matplotlibseaborn中 ,您可以仅在绘图时更改绘图设置吗?

import numpy as np
import matplotlib.pyplot as plt

plt.figure()

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'ko-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

import seaborn as sns

plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()

在此处输入图片说明

Perhaps I don't understand your question entirely. 也许我不完全理解您的问题。 Is this 'beautification' function complex?... 这个“美化”功能复杂吗?...

A possible solution is 一个可能的解决方案是

import matplotlib.pyplot as plt

# Create two subplots horizontally aligned (one row, two columns)
fig, ax = plt.subplots(1,2)
# Note that ax is now an array consisting of the individual axis

ax[0].plot(data1) 
ax[1].plot(data2)

However, in order to work data1,2 needs to be data. 但是,为了工作数据data1,2 ,必须是数据。 If you have a function which already plots the data for you I would recommend to include an axis argument to your function. 如果您有一个已经为您绘制数据的函数,我建议在函数中包含一个axis参数。 For example 例如

def my_plot(data,ax=None):
    if ax == None:
        # your previous code
    else:
        # your modified code which plots directly to the axis
        # for example: ax.plot(data)

Then you can plot it like 然后你可以像画

import matplotlib.pyplot as plt

# Create two subplots horizontally aligned
fig, ax = plt.subplots(2)
# Note that ax is now an array consisting of the individual axis

my_plot(data1,ax=ax[0])
my_plot(data2,ax=ax[1])

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

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