Пределы осей для точечной диаграммы — Matplotlib

У меня та же проблема, представленная здесь, однако предложенное решение не сработало для меня.

Я рисую набор данных, основной график которых имеет этот шаблон:

введите здесь описание изображения

Это график, пределы оси которого варьируются от (-1, 1) как по x, так и по y, с полем, установленным с помощью этого фрагмента кода:

plt.figure()
plt.show(data)
## Add some margin
l, r, b, t = plt.axis()
dx, dy = r-l, t-b
plt.axis([l-0.1*dx, r+0.1*dx, b-0.1*dy, t+0.1*dy])

Проблема в том, что у меня более "сложный" сюжет, в который мне пришлось внести некоторые изменения. Это код, который его производит:

def plot_quiver_singularities(min_points, max_points, vector_field_x, vector_field_y, file_path):
    """
    Plot the singularities of vector field
    :param file_path : the path to save the data
    :param vector_field_x : the vector field x component to be plot
    :param vector_field_y : the vector field y component to be plot
    :param min_points : a set (x, y) of min points field
    :param max_points : a set (x, y) of max points  field
    """
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_axes([.13, .3, .6, .6])

    ## Plot quiver
    x, y = numpy.mgrid[-1:1:100*1j, -1:1:100*1j]
    m = numpy.sqrt(numpy.power(vector_field_x, 2) + numpy.power(vector_field_y, 2))
    quiver = ax.quiver(x, y, vector_field_x, vector_field_y, m, zorder=1)

    ## Plot critical points
    x = numpy.linspace(-1, 1, x_steps)
    y = numpy.linspace(-1, 1, y_steps)

    # Draw the min points
    x_indices = numpy.nonzero(min_points)[0]
    y_indices = numpy.nonzero(min_points)[1]
    ax.scatter(x[x_indices], y[y_indices], marker='$\\circlearrowright$', s=100, zorder=2)

    # Draw the max points
    x_indices = numpy.nonzero(max_points)[0]
    y_indices = numpy.nonzero(max_points)[1]
    ax.scatter(x[x_indices], y[y_indices], marker='$\\circlearrowleft$', s=100, zorder=2)

    ## Put legends
    marker_min = plt.Line2D((0, 0), (0, 0), markeredgecolor=(1.0, 0.4, 0.0), linestyle='',
                            marker='$\\circlearrowright$', markeredgewidth=1, markersize=10)
    marker_max = plt.Line2D((0, 0), (0, 0), markeredgecolor=(0.2, 0.2, 1.0), linestyle='',
                            marker='$\\circlearrowleft$', markeredgewidth=1, markersize=10)
    plt.legend([marker_min, marker_max], ['CW rot. center', 'CCW rot. center'], numpoints=1,
               loc='center left', bbox_to_anchor=(1, 0.5))

    quiver_cax = fig.add_axes([.13, .2, .6, .03])
    fig.colorbar(quiver, orientation='horizontal', cax=quiver_cax)

    ## Set axis limits
    plt.xlim(-1, 1)
    plt.ylim(-1, 1)

    ## Add some margin
    # l, r, b, t = plt.axis()
    # dx, dy = r-l, t-b
    # plt.axis([l-0.1*dx, r+0.1*dx, b-0.1*dy, t+0.1*dy])

    plt.savefig(file_path + '.png', dpi=dpi)
    plt.close()

Получается следующее изображение:

введите здесь описание изображения

Как видно, пределы осей не соблюдаются, и я пока не нашел почему.

Любая помощь будет оценена по достоинству.

Заранее спасибо.


person pceccon    schedule 26.07.2014    source источник
comment
Немного не уверен, порядок играет роль? Вы поместили цветную полосу после последней команды оси. Хотите попробовать удалить его?   -  person Dan    schedule 27.07.2014
comment
Да, я пытался это сделать. Результат тот же. Проблема возникает, когда я вызываю функцию разброса.   -  person pceccon    schedule 27.07.2014
comment
отключите автомасштабирование или просто переустановите ограничения на то, что вы хотите после вызова scatter.   -  person tacaswell    schedule 28.07.2014
comment
Привет, @tcaswell. Я не занимаюсь переустановкой ограничений: plt.xlim(-1, 1), plt.ylim(-1, 1)? Спасибо.   -  person pceccon    schedule 28.07.2014
comment
На самом деле я не читал ваш код (потому что его слишком много, что не имеет отношения к вашему вопросу). Не используйте plt в функциях, так как это легко для того, что вы считаете текущими осями, и что pyplot считает текущими осями, чтобы рассинхронизироваться. Попробуйте использовать ax.set_xlim и ax.set_ylim.   -  person tacaswell    schedule 28.07.2014


Ответы (2)


Я смог решить проблему, вставив этот фрагмент кода

plt.xlim(-1, 1)
plt.ylim(-1, 1)

Сразу после звонка scatter().

person pceccon    schedule 29.07.2014

Вы также можете установить их для объекта ax:

ax.set_xlim((-1,1))
ax.set_ylim((-1,1))
person Lucas Aimaretto    schedule 13.03.2018