首页 > 解决方案 > 如何用不同的 x 和 y 在两条线之间填充?

问题描述

如何用不同的 x 和 y 在两条线之间填充?现在,填充是针对具有共同 x 轴的两个 y 函数,这是不正确的。当我尝试 x1、x2、y1、y2 时,我得到的结果比下面显示的要差。

import matplotlib.pyplot as plt
import numpy as np
from numpy import exp, sin

def g(y):
    amp = 0.6
    return amp*exp(-2.5*y)*sin(9.8*y)

def g_e(y):
    amp = 0.66
    return amp*exp(-2.5*y_e)*sin(8.1*y_e)

y = np.linspace(0, 0.83, 501)
y_e = np.linspace(0, 1.08, 501)
values = g(y)
values_e = g_e(y)

theta = np.radians(-65.9)
c, s = np.cos(theta), np.sin(theta)
rot_matrix = np.array(((c, s), (-s, c)))
xy = np.array([y, values]).T @ rot_matrix

theta_e = np.radians(-60)
c_e, s_e = np.cos(theta_e), np.sin(theta_e)
rot_matrix_e = np.array(((c_e, s_e), (-s_e, c_e)))
xy_e = np.array([y, values_e]).T @ rot_matrix_e

fig, ax = plt.subplots(figsize=(5,5))
ax.axis('equal')

x_shift = 0.59
y_shift = 0.813
x_shift_e = 0.54
y_shift_e = 0.83

ax.plot(xy[:, 0]+x_shift, xy[:, 1]+y_shift, c='red')
ax.plot(xy_e[:, 0]+x_shift_e, xy_e[:, 1]+y_shift_e, c='black')
ax.fill_between(xy[:, 0]+x_shift, xy[:, 1]+y_shift, xy_e[:, 1]+y_shift_e)
plt.show()

在此处输入图像描述

附加问题的脚本:

for i in range(len(x)-1):
    for j in range(i-1):
        xs_ys = intersection(x[i],x[i+1],x[j],x[j+1],y[i],y[i+1],y[j],y[j+1])
        if xs_ys in not None:
            xs.append(xs_ys[0])
            ys.append(xs_ys[1])

我收到一个错误:

    if xs_ys in not None:
                  ^
SyntaxError: invalid syntax

标签: python-3.xmatplotlib

解决方案


这是一种通过将一条曲线的反向连接到另一条曲线来创建“多边形”的方法。ax.fill()可用于填充多边形。请注意,fill_between()当 x 值没有很好地排序时(如旋转后的情况),这看起来很奇怪。此外,在这种情况下,镜像功能fill_betweenx()也不够用。

import matplotlib.pyplot as plt
import numpy as np

def g(y):
    amp = 0.6
    return amp * np.exp(-2.5 * y) * np.sin(9.8 * y)

def g_e(y):
    amp = 0.66
    return amp * np.exp(-2.5 * y_e) * np.sin(8.1 * y_e)

y = np.linspace(0, 0.83, 501)
y_e = np.linspace(0, 1.08, 501)
values = g(y)
values_e = g_e(y)

theta = np.radians(-65.9)
c, s = np.cos(theta), np.sin(theta)
rot_matrix = np.array(((c, s), (-s, c)))
xy = np.array([y, values]).T @ rot_matrix

theta_e = np.radians(-60)
c_e, s_e = np.cos(theta_e), np.sin(theta_e)
rot_matrix_e = np.array(((c_e, s_e), (-s_e, c_e)))
xy_e = np.array([y, values_e]).T @ rot_matrix_e

fig, ax = plt.subplots(figsize=(5, 5))
ax.axis('equal')

x_shift = 0.59
y_shift = 0.813
x_shift_e = 0.54
y_shift_e = 0.83

xf = np.concatenate([xy[:, 0] + x_shift, xy_e[::-1, 0] + x_shift_e])
yf = np.concatenate([xy[:, 1] + y_shift, xy_e[::-1, 1] + y_shift_e])

ax.plot(xy[:, 0] + x_shift, xy[:, 1] + y_shift, c='red')
ax.plot(xy_e[:, 0] + x_shift_e, xy_e[:, 1] + y_shift_e, c='black')
ax.fill(xf, yf, color='dodgerblue', alpha=0.3)
plt.show()

结果图


推荐阅读