【问题标题】:Plotting with Matplotlib results in -90 rotated plots - Python使用 Matplotlib 绘图会产生 -90 个旋转图 - Python
【发布时间】:2014-05-31 00:01:57
【问题描述】:

我在经常使用 Matplotlib 绘图时遇到过这种“问题” (Same data saved generate different images - Python)。 例如,我创建了一个带有 numpy 数组的向量场,如下所示:

def generate_divergent_free_component(sigma, x_dim, y_dim, steps):
    divergent_free_vector_field_x = numpy.zeros((steps, steps), float)
    divergent_free_vector_field_y = numpy.zeros((steps, steps), float)

    u0 = numpy.random.uniform()
    x0 = 1.0 + sigma * u0
    y0 = sigma * u0

    dx = x_dim/float(steps)
    dy = y_dim/float(steps)

    for x, y in product(range(steps), range(steps)):
        x_norm = -x_dim/2.0 + x * dx
        y_norm = -y_dim/2.0 + y * dy
        exp0 = -(math.pow(x_norm - x0, 2) + math.pow(y_norm - y0, 2)) / 2.0

        divergent_free_vector_field_x[x, y] = -(x_norm - x0) * math.exp(exp0)
        divergent_free_vector_field_y[x, y] = -(y_norm - y0) * math.exp(exp0)

    return divergent_free_vector_field_x, divergent_free_vector_field_y

我做了一些测试,在我看来 ndarrays 遵循行主要顺序,我正在按照这种模式对它们进行迭代。

但是,当使用 Matplotlib 绘图时,我将图像逆时针旋转了 90 度。

def plot_streamlines(file_path, x_dim, y_dim, steps, vector_field_x, vector_field_y, scalar_field=None):
    plt.figure()

    y, x = numpy.mgrid[-x_dim/2:x_dim/2:steps*1j, -y_dim/2:y_dim/2:steps*1j]

    plt.figure()

    # x, y : 1d arrays, an evenly spaced grid.
    # u, v : 2d arrays
    # x and y-velocities. Number of rows should match length of y, and the number of columns should match x.
    plt.streamplot(x, y, vector_field_x, vector_field_y, cmap=plt.cm.autumn)
    plt.savefig(file_path + '.png')
    plt.close()

例如,我得到了这张图片:

但我期待(和其他程序,如 Matlab)这样的图像(我现在只是在我的计算机中旋转它,但我期待的是我圈出的点,如下图所示):

所以我想知道 Matplotlib 是否可以工作或期望以列为主的顺序或类似的东西......我只是想了解它是如何正常工作的。

任何帮助将不胜感激。

提前谢谢你。

【问题讨论】:

    标签: python numpy matplotlib plot rotation


    【解决方案1】:

    问题似乎是plt.streamplot 希望divergent_free_vector_field 数组被索引[y, x],而不是[x, y]

    一个好的测试是在xy 中使用不同的步长。当您尝试绘图时,您应该在网格形状上获得AssertionError,因为它期望行数与y 的大小相同,列数与@987654330 的大小相同@。

    尝试将其更改为:

    divergent_free_vector_field_x = numpy.zeros((steps_y, steps_x), float)
    divergent_free_vector_field_y = numpy.zeros((steps_y, steps_x), float)
    ...
    divergent_free_vector_field_x[y, x] = -(x_norm - x0) * math.exp(exp0)
    divergent_free_vector_field_y[y, x] = -(y_norm - y0) * math.exp(exp0)
    

    【讨论】:

    • 这是我想的,但我在文档中找不到。现在我想用两种不同的方法绘制我的矢量场,但我无法让它们匹配(stackoverflow.com/questions/23965477/…)。我很怀疑是否坚持使用 Matploblib。 :S
    • @pceccon 我同意文档不是很清楚。它说的是关于 u 和 v:uv:二维数组 x 和 y 速度。 行数应该匹配y的长度,列数应该匹配x。
    猜你喜欢
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多