В этой статье мы узнаем, как повернуть текст в Matplotlib на Python. Из множества параметров в matplotlib.text() есть три основных параметра, которые будут определять поворот текста и способ поворота текста.
Синтаксис метода matplotlib.text
Syntax: matplotlib.text(x=0, y=0, text=”, rotation=None, rotation_mode=None, transform_rotates_text=False)
Параметр:
- X, Y: x and y coordinate value
- text: str,Text value
- rotation: float or {‘vertical’, ‘horizontal’}, Defines the angle in degrees between 0-360 for the text to rotate. ‘+ve’ values for rotating the text anticlockwise and ‘-ve’ values rotates the text clockwise. ‘horizontal’ = 0, ‘vertical’ = 90.
- rotation_mode: {None, ‘default’, ‘anchor’}, Specifies the text rotation mode. None or “default”: text is rotated first, then aligned performed.
- anchor: rotation of the text occurs after alignment.
- transform_rotates_text: bool
Return: влияет ли поворот преобразования на направление текста.
Поэтапная реализация
Теперь мы можем добавить эти параметры и изменить их значения, поскольку мы хотим повернуть текст на графике.
Шаг 1: Импортируйте библиотеку
Python3
import
matplotlib.pyplot as plt
Шаг 2: Установите диапазон осей x и y.
Python3
plt.xlim(
0
,
3
)
plt.ylim(
0
,
5
)
Шаг 3: Построение линии для справки.
Python3
plt.plot((
1
,
4
), (
1
,
1
),
'b'
)
Шаг 4: Вставьте текст обычным цветом.
Python3
plt.text(
1
,
1
,
'(1) Geeks_for_Geeks'
, color
=
'green'
)
Шаг 5: Вставьте текст, повернутый по умолчанию.
Python3
plt.text(
1
,
2
,
'(3) Geeks_for_Geeks 30°'
,
color
=
'green'
, rotation
=
30
,
rotation_mode
=
'anchor'
)
Шаг 6: Вставьте текст, повернутый относительно координат графика.
Python3
plt.text(
1
,
1.5
,
'(2) Geeks_for_Geeks 30° relative'
,
color
=
'green'
, rotation
=
30
,
rotation_mode
=
'anchor'
,
transform_rotates_text
=
True
)
Complete Code:
На рисунке видно, что (1) — это обычный текст, размещенный горизонтально на графике, (2) — текст, повернутый на 30° относительно координат графика, и (3) — текст, повернутый на 30° по умолчанию.
Python3
# Text rotation relative to line in matplotlib
import
matplotlib.pyplot as plt
# setting x and y axis range
plt.xlim(
0
,
3
)
plt.ylim(
0
,
5
)
# plotting a line for reference
# plt.plot((1, 4), (1, 1), 'b')
# inserting text normally
plt.text(
1
,
1
,
'(1) Geeks_for_Geeks'
, color
=
'green'
)
# Inserting text rotated default
plt.text(
1
,
2
,
'(3) Geeks_for_Geeks 30°'
, color
=
'green'
,
rotation
=
30
, rotation_mode
=
'anchor'
)
# Inserting text rotated relatively to plot coordinates
plt.text(
1
,
1.5
,
'(2) Geeks_for_Geeks 30° relative'
,
color
=
'green'
,
rotation
=
30
, rotation_mode
=
'anchor'
,
transform_rotates_text
=
True
)
# Display plot
plt.show()
Вывод: