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)
它有点冗长,但它更清晰,更容易跟踪,特别是有几个数字,每个都有多个子图.
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样式")开始到文档).
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所需轴对象的手柄将聚焦在该轴上.
(还没有评论权限,抱歉新答案!)
这里接受的答案是使用面向对象的接口( 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仅支持单个图形的内部状态相关的问题。
| 归档时间: |
|
| 查看次数: |
276151 次 |
| 最近记录: |