使用列表理解绘制单独的图形
Plotting separate figures using list comprehension
我当前的代码为列表 test 中的每个元素生成重叠图形。如何使用列表理解生成两个单独的图形? (最好只使用一行代码)。
test=[[1, 2, 3, 4],[5, 6, 7, 8]]
[plt.plot(test[k]) for k in range(0,2)]
当前输出如下所示:
如 Matplotlib Usage Guide 中所述,plt.plot
的工作方式与 ax.plot
绘图方法相同:
for each Axes graphing method, there is a corresponding function in the matplotlib.pyplot module that performs that plot on the "current" axes, creating that axes (and its parent figure) if they don't exist yet.
因此,当您 运行 作为示例给出的列表理解时,for
循环中的第一个 plt.plot
方法调用会创建一个新的 figure object containing a child Axes object. Then, as noted in the Matplotlib Pyplot tutorial section on working with multiple figures and axes:
MATLAB, and pyplot, have the concept of the current figure and the current axes. All plotting functions apply to the current axes.
这就是循环中所有后续 plt.plot
调用都绘制在同一张图中的原因。要在单独的图形中绘制线条,必须为每个 plt.plot
调用创建一个新图形,如下所示:
test = [[1, 2, 3, 4],[5, 6, 7, 8]]
for k in range(len(test)): plt.figure(), plt.plot(test[k])
编辑:根据 JohanC(关于问题)的评论,将列表理解替换为单行复合语句。尽管这违背了PEP 8 recommendations,但它确实使代码在满足单行要求的同时更具可读性。
我当前的代码为列表 test 中的每个元素生成重叠图形。如何使用列表理解生成两个单独的图形? (最好只使用一行代码)。
test=[[1, 2, 3, 4],[5, 6, 7, 8]]
[plt.plot(test[k]) for k in range(0,2)]
当前输出如下所示:
如 Matplotlib Usage Guide 中所述,plt.plot
的工作方式与 ax.plot
绘图方法相同:
for each Axes graphing method, there is a corresponding function in the matplotlib.pyplot module that performs that plot on the "current" axes, creating that axes (and its parent figure) if they don't exist yet.
因此,当您 运行 作为示例给出的列表理解时,for
循环中的第一个 plt.plot
方法调用会创建一个新的 figure object containing a child Axes object. Then, as noted in the Matplotlib Pyplot tutorial section on working with multiple figures and axes:
MATLAB, and pyplot, have the concept of the current figure and the current axes. All plotting functions apply to the current axes.
这就是循环中所有后续 plt.plot
调用都绘制在同一张图中的原因。要在单独的图形中绘制线条,必须为每个 plt.plot
调用创建一个新图形,如下所示:
test = [[1, 2, 3, 4],[5, 6, 7, 8]]
for k in range(len(test)): plt.figure(), plt.plot(test[k])
编辑:根据 JohanC(关于问题)的评论,将列表理解替换为单行复合语句。尽管这违背了PEP 8 recommendations,但它确实使代码在满足单行要求的同时更具可读性。