计算由直线段连接的坐标点包围的面积

时间:2018-11-26 17:29:56

标签: python python-3.x numpy matplotlib

我正在尝试计算由直线段连接的一组坐标点之间的面积。下图是绘图:

enter image description here

该图是使用以下代码生成的:

def data():

    Cp_AoA_6=[0.833,-0.833,-0.467,-0.167,0.000,0.000,0.000,0.000,0.000,-0.167,0.833,2.167,1.833,1.500,1.000,0.667,0.500,0.333,0.167,-0.167]

    Cp_AoA_16=[-4.667,-1.000,-0.833,-0.500,-0.167,0.000,0.000,0.167,0.333,0.667,-4.667,0.667,0.667,0.667,0.667,0.667,0.667,0.667,0.667,0.667]

    x_c=[0.000,0.028,0.044,0.109,0.207,0.354,0.520,0.696,0.847,1.000,0.000,0.028,0.044,0.109,0.207,0.354,0.520,0.698,0.849,1.000]

    return(Cp_AoA_6,Cp_AoA_16,x_c)

def plot():
    x_lower = data()[2][0:10]
    x_upper = data()[2][10:20]
    y_lower = data()[0][0:10]
    y_upper = data()[0][10:20]
    scale_y = 1
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x_lower,y_lower, '-ob')
    ax.plot(x_upper,y_upper, '-ob')

    plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1],
        [r'$0$', r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$', r'$1$'])

    ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
    ax.yaxis.set_major_formatter(ticks_y)

    plt.title("Pressure Versus Postion for an AoA of 6°")
    ax.set_xlabel("x/c ($m$)")
    ax.set_ylabel("Coefficient of Pressure")
    plt.legend()
    plt.grid(True)
    return(None)

plot()

如何找到直线段包围的区域?

1 个答案:

答案 0 :(得分:1)

假设您可以接受使用numpy,则只需从顶行np.trapz(y_upper, x=x_upper) - np.trapz(y_lower, x=x_lower)减去底行的梯形积分即可得到。

在下面粘贴示例数据,这些数据返回area: 0.6880585

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

def data():

    Cp_AoA_6=[0.833,-0.833,-0.467,-0.167,0.000,0.000,0.000,0.000,0.000,-0.167,0.833,2.167,1.833,1.500,1.000,0.667,0.500,0.333,0.167,-0.167]

    Cp_AoA_16=[-4.667,-1.000,-0.833,-0.500,-0.167,0.000,0.000,0.167,0.333,0.667,-4.667,0.667,0.667,0.667,0.667,0.667,0.667,0.667,0.667,0.667]

    x_c=[0.000,0.028,0.044,0.109,0.207,0.354,0.520,0.696,0.847,1.000,0.000,0.028,0.044,0.109,0.207,0.354,0.520,0.698,0.849,1.000]

    return(Cp_AoA_6,Cp_AoA_16,x_c)

def enclosed_area(x_lower, y_lower, x_upper, y_upper):
    return(np.trapz(y_upper, x=x_upper) - np.trapz(y_lower, x=x_lower))

def plot():
    x_lower = data()[2][0:10]
    x_upper = data()[2][10:20]
    y_lower = data()[0][0:10]
    y_upper = data()[0][10:20]

    scale_y = 1
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x_lower,y_lower, '-ob')
    ax.plot(x_upper,y_upper, '-ob')

    plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1],
        [r'$0$', r'$0.2$', r'$0.4$', r'$0.6$', r'$0.8$', r'$1$'])

    ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
    ax.yaxis.set_major_formatter(ticks_y)

    plt.title("Pressure Versus Postion for an AoA of 6°")
    ax.set_xlabel("x/c ($m$)")
    ax.set_ylabel("Coefficient of Pressure")
    plt.grid(True)
    plt.show()

    print("area: " + str(enclosed_area(x_lower, y_lower, x_upper, y_upper)))

    return(None)

plot()