我如何告诉Matplotlib创建第二个(新)情节,然后在旧照片上绘图?

Pet*_*r D 123 python plot matplotlib figure

我想绘制数据,然后创建一个新的数字和绘制数据2,最后回到原始绘图和绘图data3,有点像这样:

import numpy as np
import matplotlib as plt

x = arange(5)
y = np.exp(5)
plt.figure()
plt.plot(x, y)

z = np.sin(x)
plt.figure()
plt.plot(x, z)

w = np.cos(x)
plt.figure("""first figure""") # Here's the part I need
plt.plot(x, w)
Run Code Online (Sandbox Code Playgroud)

仅供参考我如何告诉matplotlib我已经完成了一个情节?做类似的事情,但并不完全!它不允许我访问原始情节.

sim*_*onb 141

如果您发现自己经常这样做,那么可能值得研究matplotlib的面向对象接口.在你的情况下:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")

z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)

w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis
Run Code Online (Sandbox Code Playgroud)

它有点冗长,但它更清晰,更容易跟踪,特别是有几个数字,每个都有多个子图.

  • 我更喜欢面向对象的方法,因为当我预期有很多数字时,通过使用名称而不是数字来跟踪它们会更容易.谢谢! (2认同)
  • @GeorgeDatseris语法略有不同.它是`ax1.set_xlabel("你的x标签")`,`ax1.set_ylabel("你的y标签")`和`ax1.set_title("你的标题")`. (2认同)
  • @yashSodha-这是子图数量(行,列,索引)的matlab样式规范。但是现在使用`plt.subplots(nrows,ncols)`要容易得多。更新了示例。 (2认同)

agf*_*agf 98

打电话时figure,只需为情节编号即可.

x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)

z = np.sin(x)
plt.figure(1)
plt.plot(x, z)

w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,您可以根据需要对图形进行编号(此处,从开始0),但如果在创建新图形时根本不提供图形编号,则自动编号将从1("Matlab样式")开始到文档).

  • 这似乎在matplotlib的交互模式下工作,而figure()... add_subplot()方法则没有.谢谢! (3认同)
  • @SebMa 请不要在不理解代码的情况下更改代码。这个答案具体是关于将数字传递给您删除的“figure”。您更改的其他内容是从原始帖子中复制的,而不是我的答案中的错误。 (2认同)

Ros*_* B. 14

但是,编号从1,开始,所以:

x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)

z = np.sin(x)
plt.figure(2)
plt.plot(x, z)

w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)
Run Code Online (Sandbox Code Playgroud)

此外,如果图形上有多个轴,例如子图,请使用axes(h)命令,其中h所需轴对象的手柄将聚焦在该轴上.

(还没有评论权限,抱歉新答案!)

  • `0`有效,_automatic_编号只是从'1'开始,如果你根本不给它一个数字. (10认同)

c z*_*c z 5

这里接受的答案是使用面向对象的接口( matplotlib),但答案本身包含了一些MATLAB 风格的接口( matplotib.pyplot)。

如果您喜欢这种方式,可以单独使用 OOP方法:

import numpy as np
import matplotlib

x = np.arange(5)
y = np.exp(x)
first_figure      = matplotlib.figure.Figure()
first_figure_axis = first_figure.add_subplot()
first_figure_axis.plot(x, y)

z = np.sin(x)
second_figure      = matplotlib.figure.Figure()
second_figure_axis = second_figure.add_subplot()
second_figure_axis.plot(x, z)

w = np.cos(x)
first_figure_axis.plot(x, w)

display(first_figure) # Jupyter
display(second_figure)
Run Code Online (Sandbox Code Playgroud)

这使用户可以手动控制图形,并避免与pyplot仅支持单个图形的内部状态相关的问题。