Введение
В Matplotlib можно настроить положение оси spines, чтобы настроить внешний вид графика. В этом лабе вы узнаете, как настроить положение spines в Matplotlib.
Советы по ВМ
После запуска ВМ нажмите в левом верхнем углу, чтобы переключиться на вкладку Notebook и получить доступ к Jupyter Notebook для практики.
Иногда вам может потребоваться подождать несколько секунд, пока Jupyter Notebook загрузится. Валидация операций не может быть автоматизирована из-за ограничений Jupyter Notebook.
Если вы сталкиваетесь с проблемами во время обучения, не стесняйтесь обращаться к Labby. Оставьте отзыв после занятия, и мы оперативно решим проблему для вас.
Импортируем необходимые библиотеки
В этом шаге мы импортируем необходимые библиотеки для создания наших графиков.
import matplotlib.pyplot as plt
import numpy as np
Создаем базовый график
В этом шаге мы создадим базовый график, чтобы продемонстрировать различные варианты расположения spines в Matplotlib.
x = np.linspace(0, 2*np.pi, 100)
y = 2 * np.sin(x)
fig, ax_dict = plt.subplot_mosaic(
[['center', 'zero'],
['axes', 'data']]
)
fig.suptitle('Spine positions')
ax = ax_dict['center']
ax.set_title("'center'")
ax.plot(x, y)
ax.spines[['left', 'bottom']].set_position('center')
ax.spines[['top', 'right']].set_visible(False)
ax = ax_dict['zero']
ax.set_title("'zero'")
ax.plot(x, y)
ax.spines[['left', 'bottom']].set_position('zero')
ax.spines[['top', 'right']].set_visible(False)
ax = ax_dict['axes']
ax.set_title("'axes' (0.2, 0.2)")
ax.plot(x, y)
ax.spines.left.set_position(('axes', 0.2))
ax.spines.bottom.set_position(('axes', 0.2))
ax.spines[['top', 'right']].set_visible(False)
ax = ax_dict['data']
ax.set_title("'data' (1, 2)")
ax.plot(x, y)
ax.spines.left.set_position(('data', 1))
ax.spines.bottom.set_position(('data', 2))
ax.spines[['top', 'right']].set_visible(False)
Определяем метод для настройки расположения spines
В этом шаге мы определим метод, который настраивает расположение осевых spines в соответствии с указанными расположениями spines.
def adjust_spines(ax, spines):
"""
Adjusts the location of the axis spines based on the specified spine locations.
Parameters:
ax (Axes): The Matplotlib Axes object to adjust the spines for.
spines (list of str): The desired spine locations. Valid options are 'left', 'right', 'top', 'bottom'.
Returns:
None
"""
for loc, spine in ax.spines.items():
if loc in spines:
spine.set_position(('outward', 10)) ## move the spine outward by 10 points
else:
spine.set_color('none') ## don't draw the spine
## turn off ticks where there is no spine
if 'left' in spines:
ax.yaxis.set_ticks_position('left')
else:
ax.yaxis.set_ticks([])
if 'bottom' in spines:
ax.xaxis.set_ticks_position('bottom')
else:
ax.xaxis.set_ticks([])
Создаем график с использованием метода adjust_spines
В этом шаге мы создадим график с использованием метода adjust_spines, чтобы продемонстрировать, как настраивать расположение spines.
fig = plt.figure()
x = np.linspace(0, 2 * np.pi, 100)
y = 2 * np.sin(x)
ax = fig.add_subplot(2, 2, 1)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['left'])
ax = fig.add_subplot(2, 2, 2)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, [])
ax = fig.add_subplot(2, 2, 3)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['left', 'bottom'])
ax = fig.add_subplot(2, 2, 4)
ax.plot(x, y, clip_on=False)
adjust_spines(ax, ['bottom'])
plt.show()
Резюме
В этом практическом занятии мы узнали, как настраивать расположение spines в Matplotlib, устанавливая позицию осевых spines с использованием метода set_position, и как определить метод для настройки расположения spines в соответствии с желаемыми расположениями spines. Это может быть полезно для настройки внешнего вида графиков и выделения конкретных особенностей.