在matlab中,您可以随时返回到任何图,更新或添加到它中使用comand figure(the_figure_number);

这在for循环中非常有用,例如

x=0:0.2:20;
for n=[1 2 3 4]
    figure(1);
    plot(x,n*x);
    hold on
    figure(2);
    plot(x,x.^n);
    hold on
end

前面的代码将生成2个图形,每个图形与4个图形共享轴.

在Python中使用matplotlib,这看起来很难实现(Python不是很好). 有没有一种方法来实现这一点,而不使用子图或更糟糕的是单独的for循环?

我想要绘制的真实数据太大,所以多个for循环非常慢,加上为了发布目的,每个图都需要有自己的. svg文件,所以子图很不方便.

推荐答案

我认为你可以使用与matlab相同的代码 struct 得到相同的行为.下面的代码将生成两个图,每个图有4个图,而不使用子图. 在matplotlib中,子图用于在同一图形上显示多个图形,但这里您希望在同一图形上添加多个图形. 你可以回到一个数字添加图例,标题,定义轴限制,显示任何格式,如网格,股票等.

import numpy as np
import matplotlib.pyplot as plt

# Create the x vector
x = np.arange(0, 20.2, 0.2)

# Loop over the values of n
for n in [1, 2, 3, 4]:
    # Plot n*x for each n in the first figure
    plt.figure(1)
    plt.plot(x, n*x, label=f'n={n}')

    # Plot x^n for each n in the second figure
    plt.figure(2)
    plt.plot(x, x**n, label=f'n={n}')

# Format the first figure
# title, legends, grids, tickers, axis limits, colors, ...
plt.figure(1)
plt.legend()
plt.title('n*x for n in [1, 2, 3, 4]')
plt.xlabel('x')
plt.ylabel('n*x')

# Format the second figure.
plt.figure(2)
plt.legend()
plt.title('x^n for n in [1, 2, 3, 4]')
plt.xlabel('x')
plt.ylabel('x^n')

# Show all figures
plt.show()

Python相关问答推荐

如何根据日期和时间将状态更新为已过期或活动?

如何从具有多个嵌入选项卡的网页中Web抓取td类元素

使用LineConnection动画1D数据

沿着数组中的轴计算真实条目

pandas滚动和窗口中有效观察的最大数量

如何在类和classy-fastapi -fastapi- followup中使用FastAPI创建路由

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

在pandas中使用group_by,但有条件

给定高度约束的旋转角解析求解

不能使用Gekko方程'

使用特定值作为引用替换数据框行上的值

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

旋转多边形而不改变内部空间关系

导入错误:无法导入名称';操作';

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

语法错误:文档. evaluate:表达式不是合法表达式

Python Mercury离线安装

Matplotlib中的曲线箭头样式

如何将列表从a迭代到z-以抓取数据并将其转换为DataFrame?

高效地计算数字数组中三行上三个点之间的Angular