【问题标题】:Plot something in one figure, and use it again later for another figure在一个图中绘制一些东西,稍后再将它用于另一个图
【发布时间】:2018-02-02 08:07:33
【问题描述】:

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

我有一个 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,其中包含三个数字)

【问题讨论】:

  • 您的问题来对了地方,是的。但是,尚不清楚您到底要达到什么目的。可能这仅仅是由于您所说的“早期创建的情节中的三个”的措辞。您的定义中的“情节”是什么?如我所见,上面的代码创建了 2 个数字。每个图有 2 个子图。因此,您最终总共有 4 个地块。您是否想在新图中使用这 4 个图中的 3 个?如果是这样,您希望如何选择您使用的那些?
  • 你好@ImportanceOfBeingErnest,好吧,我从这段代码中得到了2个数字,其中有一个视图图。之后我想要第三个数字,其中两个原始数字组合在一起(一个在另一个之上)。

标签: python numpy matplotlib subplot


【解决方案1】:

在 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输出:

【讨论】:

  • 非常感谢。我得到了它,即使它需要一些工作,因为我的原始代码稍微复杂一些;)
猜你喜欢
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 2022-12-24
  • 1970-01-01
  • 2021-10-21
  • 2016-05-20
相关资源
最近更新 更多