Matplotlib - настройка rcParams для перемещения xlabel наверх? - PullRequest
1 голос
/ 06 августа 2020

Мне нужно, чтобы на всех моих фигурах были xlabel, xticks и xticklabels вверху. С тех пор я написал функцию для настройки plt.rcParams, которая служит для инициализации.

Однако, похоже, нет такого параметра для установки xlabel наверх заранее. Вот упрощенная демонстрация:

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['xtick.bottom'] = False
plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = True
plt.rcParams['xtick.labeltop'] = True

data = np.arange(9).reshape((3,3))

f,ax = plt.subplots()
ax.imshow(data)
ax.set_xlabel('x label')
ax.set_ylabel('y label')

Вывод: enter image description here

Currently the way I found to adjust it is putting ax.xaxis.set_label_position('top') after calling ax.set_xlabel('x label').

I'm looking for a solution with two goals:

  1. It change the default x-label position so that every time ax.set_xlabel() is called, it shows up at the top.
  2. This step could be executed before calling ax.set_xlabel()

So I don't have to use ax.xaxis.set_label_position() individually every time.

Extra: As @r-beginners mentioned, the официальная ссылка действительно предоставила пример. Но в вызванном ими скрипте это ax.set_title('xlabel top'), которое отличается от ax.set_xlabel('x label'). Обратите внимание, что заголовок всегда находится вверху по умолчанию, независимо от настройки plt.rcParams или нет. Полагаю, они по ошибке пропустили этот выпуск.

Ответы [ 2 ]

1 голос
/ 07 августа 2020

Насколько я могу судить, положение метки оси x жестко запрограммировано.

Давайте посмотрим на определение класса XAxis, соответствующего файл .../matplotlib/axis.py

class XAxis(Axis):
    ...
    def _get_label(self):
        # x in axes coords, y in display coords (to be updated at draw
        # time by _update_label_positions)
        label = mtext.Text(x=0.5, y=0,
                           fontproperties=font_manager.FontProperties(
                               size=rcParams['axes.labelsize'],
                               weight=rcParams['axes.labelweight']),
                           color=rcParams['axes.labelcolor'],
                           verticalalignment='top',
                           horizontalalignment='center')

        label.set_transform(mtransforms.blended_transform_factory(
            self.axes.transAxes, mtransforms.IdentityTransform()))

        self._set_artist_props(label)
        self.label_position = 'bottom'
        return label
    ...

Как видите, вертикальное положение метки жестко закодировано при вызове Text, y=0 в координатах дисплея, чтобы обновляться во время отображения на _update_label_positions, а label_position жестко запрограммирован на 'bottom'.

0 голосов
/ 06 августа 2020

Есть объяснение в официальной ссылке . Это поможет вам с этим справиться.

import matplotlib.pyplot as plt
import numpy as np

# plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
# plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True

x = np.arange(10)

fig, ax = plt.subplots()

ax.plot(x)
ax.set_xlabel('xlabel top')  # Note title moves to make room for ticks

secax = ax.secondary_xaxis('top')
secax.set_xlabel('new label top')

plt.show()

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...