【问题标题】:Plotting piecewise contour graph in Python在 Python 中绘制分段等高线图
【发布时间】:2019-02-26 10:05:53
【问题描述】:

我想在 Python 中绘制一个分段函数,其中有两个变量 xy。这意味着我需要某种等高线图。在 Matlab 中可以使用

syms x y
eq1 = 0.1*(x/2)^2-0.3*(y/4)^2; 
eq2 = 0.15*(x/3)^2-0.25*(y/2)^2;

ezplot(eq1,[-5 5 -10 10]);
hold on
ezplot(eq2,[-4 4 -5 5]);

其中ezplotxmin < x < xmaxymin < y < ymax 上绘制eq1 = 0。 Python中有任何(简单的)等效函数吗?

我查看了this post 中的解决方案。他们的问题只涉及一个变量x,所以对我的情况没有帮助。

【问题讨论】:

  • 这里没有看到函数的分段定义,你能解释的更准确点吗?
  • 对不起,我只写了一个分段函数的“片段”。 (仅供参考,这只是一个 MWE。)我添加了另一件。

标签: python matlab matplotlib plot contour


【解决方案1】:

您可以使用numpymasked array 分隔不同的部分。
首先为等高线图定义函数、x 和 y 范围及其 2D 版本:

import numpy as np
import matplotlib.pyplot as plt
from numpy.ma import masked_array as marr

def eq1(x, y):
    return 0.1*(x/2)**2-0.3*(y/4)**2
def eq2(x, y):
    return 0.15*(x/3)**2-0.25*(y/2)**2

x = np.linspace(-5, 5, 101)
y = np.linspace(-10, 10, 201)
xx, yy = np.meshgrid(x, y)

现在我们需要一个 2D 蒙版(或一些,取决于分段函数的数量)来分隔函数不同部分的定义范围:

maskx = ((xx>=-4) * (xx<=4))
masky = ((yy>=-5) * (yy<=5))
mask = maskx * masky

这可以应用于不同的掩码数组:

res1 = marr(eq1(xx, yy), mask)
res2 = marr(eq2(xx, yy), ~mask)

绘制掩码数组会将掩码为 True 的所有区域留空:

fig, axs = plt.subplots(1, 2, sharey=True)
axs[0].contour(xx, yy, res1)
axs[0].contour(xx, yy, res2)
axs[0].set_title('contour')
axs[1].contourf(xx, yy, res1)
axs[1].contourf(xx, yy, res2)
axs[1].set_title('contourf')

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多