python - 在一个图中绘制一些东西,稍后再用于另一个图中

标签 python numpy matplotlib subplot

我希望我在正确的地方问这个问题。

我有一个 for 循环,其中创建了许多图形。 循环完成后,我想再生成一个图形,其中三个先前创建的图作为 suplots。

我现在的代码是这样的:

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)+(t/10)**2.

t1=np.arange(0.0,5.0,0.1)
t2=np.arange(0.0,5.0,0.02)


for i in range(2):
    fig= plt.figure(i)
    ax1=fig.add_subplot(111)
    plt.title('Jon Snow')
    kraft_plot,=ax1.plot(t1,np.sin(t1),color='purple')
    tyrion=ax1.axvline(2,color='darkgreen',ls='dashed')
    ax1.set_ylabel('Kraft [N]',color='purple',fontweight='bold')
    ax1.set_xlabel('Zeit [s]',fontweight='bold')
    ax2=ax1.twinx()
    strecke_plot,=ax2.plot(t2,t2/5,color='grey',label='Verlauf der Strecke')
    ax2.set_ylabel('Strecke [mm]',color='grey',fontweight='bold')
    ax1.legend((kraft_plot,tyrion,strecke_plot),('Jonny','Dwarf','andalltherest'),loc=2)

plt.show()

你能帮帮我吗?我可以保存整个图/图吗?

干杯,达洛。

编辑:它应该是这样的(右边的部分是我想要实现的): The text in the right should be normal sclaed, obviously...

问题是,我首先想单独打印数字,然后一起打印(最后我想保存为 pdf/png,其中包含三个数字)

最佳答案

在 matplotlib 中,一个轴(一个子图)总是恰好是一个图形的一部分。虽然有 options to copy an axes from one figure to another ,这是一个相当复杂的过程。相反,您可以根据需要在多个图中重新创建情节。使用一个将要绘制的坐标轴作为参数的函数,可以使这变得相当简单。

为了将所有三个图保存在 pdf 中,您可以使用 pdfPages,如代码底部所示。

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)+(t/10)**2.

t1=np.arange(0.0,5.0,0.1)
t2=np.arange(0.0,5.0,0.02)

def plot(ax, i):
    ax.set_title('Jon Snow')
    kraft_plot,=ax.plot(t1,np.sin(t1),color='purple')
    tyrion=ax.axvline(2,color='darkgreen',ls='dashed')
    ax.set_ylabel('Kraft [N]',color='purple',fontweight='bold')
    ax.set_xlabel('Zeit [s]',fontweight='bold')
    ax2=ax.twinx()
    strecke_plot,=ax2.plot(t2,t2/5,color='grey',label='Verlauf der Strecke')
    ax2.set_ylabel('Strecke [mm]',color='grey',fontweight='bold')
    ax.legend((kraft_plot,tyrion,strecke_plot),('Jonny','Dwarf','andalltherest'),loc=2)

figures=[]

for i in range(2):
    fig= plt.figure(i)
    ax1=fig.add_subplot(111)
    plot(ax1, i)
    figures.append(fig)

# create third figure
fig, (ax1,ax2) = plt.subplots(nrows=2)
plot(ax1, 0)
plot(ax2, 1)
figures.append(fig)

from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('multipage_pdf.pdf') as pdf:
    for fig in figures:
        pdf.savefig(fig)


plt.show()

三页pdf输出:

enter image description here

关于python - 在一个图中绘制一些东西,稍后再用于另一个图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45861656/

相关文章:

python - Pyplot - 当一个轴的列表长度不一致时,如何在同一个图表上绘制多条线?

python - 具有基于索引的限制的前向填充列

Python 单元测试设置函数

python - 在 pandas 数据帧 : TypeError: string indices must be integers 中的字符串后添加空格

python - 从字典列表到 np 数组数组,反之亦然

python - 更改 python matplotlib 中的子图大小

python - 为什么这段 python 代码会与自身发生冲突?

python - 如何在 Python 中使用 x^2 进行(空中飞人)集成?

python - plt.subplots() 中的 sharey ='all' 参数未传递给 df.plot()?

python - 使用 hlines 创建甘特图?