Matplotlib中的矢量和标量字段

时间:2018-01-02 12:25:46

标签: python matplotlib colormap

大家新年快乐!
我正在尝试使用 Matplotlib 箭头 pcolormesh 叠加标量和矢量字段的图形。我想要表示的数据被组织成五列的文件,前两个是节点坐标 x y ,它们是等间隔的。以下两个是矢量字段组件 vx vy ,最后一列给出了与颜色映射一起使用的标量字段 v 的值。

我想确切地说,标量映射中不应包含零 vx vz 的节点。

以下是我的数据文件示例:

0.1  0.1 -0.005  -0.0016  0.2482
0.1  0.3  0.0051 -0.0015  0.2428
0.1  0.5 -0.0002 -0.0023  0.2434
0.1  0.7 -0.004  -0.0023  0.2406
0.1  0.9 -0.0012 -0.002   0.2409
0.1  1.1 -0.0041 -0.0021  0.2393
0.1  1.3  0.0002 -0.0021  0.2404
0.1  1.5 -0.0067 -0.0025  0.237
0.1  1.7  0.0004 -0.0027  0.2387
0.1  1.9  0.0013 -0.0025  0.2387
0.3  0.1  0.0018 -0.002   0.2444
0.3  0.3  0.0105 -0.0019  0.2401
0.3  0.5  0.0031 -0.0028  0.2409
0.3  0.7 -0.0014 -0.0028  0.239
0.3  0.9  0.0009 -0.0024  0.2382
0.3  1.1  0.0013 -0.0026  0.2358
0.3  1.3  0.0021 -0.0024  0.2397
0.3  1.5 -0.0008 -0.0027  0.2386
0.3  1.7  0.0026 -0.0029  0.2394
0.3  1.9  0.0025 -0.0028  0.2395
0.5  0.1  0.0041 -0.0015  0.2485
0.5  0.3  0.0123 -0.0015  0.2439
0.5  0.5  0.0018 -0.0022  0.2454
0.5  0.7 -0.0052 -0.0022  0.2445
0.5  0.9 -0.0021 -0.002   0.2426
0.5  1.1 -0.0034 -0.0023  0.2396
0.5  1.3 -0.0027 -0.0022  0.242
0.5  1.5 -0.0077 -0.0024  0.242
0.5  1.7 -0.0006 -0.0026  0.2417
0.5  1.9 -0.0002 -0.0025  0.2409

1 个答案:

答案 0 :(得分:1)

希望它对寻找它的任何人都有用:

import matplotlib.pyplot as plt
import numpy as np


def read_data(data_file):
    # https://stackoverflow.com/questions/3277503/
    with open(data_file, 'r') as data:
        lines = data.readlines()

    x = []
    y = []
    vx = []
    vy = []
    v = []
    for line in lines:
        # https://stackoverflow.com/questions/2492415/
        numbers = [float(n) for n in line.split()]
        x.append(numbers[0])
        y.append(numbers[1])
        vx.append(numbers[2])
        vy.append(numbers[3])
        v.append(numbers[4])

    x = np.array(x)
    y = np.array(y)
    vx = np.array(vx)
    vy = np.array(vy)
    v = np.array(v)
    n_lines = 0
    i = 0
    while x[0] == x[i]:
        n_lines += 1
        i += 1
    n_cols = len(x) / n_lines
    x = x.reshape((n_cols, n_lines))
    y = y.reshape((n_cols, n_lines))
    vx = vx.reshape((n_cols, n_lines))
    vy = vy.reshape((n_cols, n_lines))
    v = v.reshape((n_cols, n_lines))
    # Change the conditions on the line bellow to what you want,
    # it should make the 'contourf' not draw on those points.
    v[(abs(vx) <= 0.002) & (abs(vy) <= 0.002)] = np.NaN
    #https://stackoverflow.com/questions/16343752/
    return x, y, vx, vy, v


def plot_all(x, y, vx, vy, v):
    # https://stackoverflow.com/questions/12079842/
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.contourf(x, y, v)
    ax.quiver(x, y, vx, vy)
    fig.show()


if __name__ == "__main__":
    data = read_data('data.txt')
    plot_all(*data)

resulting graph with white holes where v is NaN