Как мне соответствовать длинному названию? - программирование
Подтвердить что ты не робот

Как мне соответствовать длинному названию?

Там есть аналогичный вопрос - но я не могу заставить предлагаемое там решение работать.

Здесь примерный график с длинным названием:

#!/usr/bin/env python

import matplotlib
import matplotlib.pyplot
import textwrap

x = [1,2,3]
y = [4,5,6]

# initialization:
fig = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) 

# lines:
fig.add_subplot(111).plot(x, y)

# title:
myTitle = "Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all."

fig.add_subplot(111).set_title("\n".join(textwrap.wrap(myTitle, 80)))

# tight:
(matplotlib.pyplot).tight_layout()

# saving:
fig.savefig("fig.png")

он дает

 AttributeError: 'module' object has no attribute 'tight_layout'

и если я заменил (matplotlib.pyplot).tight_layout() на fig.tight_layout(), он даст:

 AttributeError: 'Figure' object has no attribute 'tight_layout'

Итак, мой вопрос: как мне соответствовать заголовку сюжета?

4b9b3361

Ответ 1

Вот что я, наконец, использовал:

#!/usr/bin/env python3

import matplotlib
from matplotlib import pyplot as plt
from textwrap import wrap

data = range(5)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(data, data)

title = ax.set_title("\n".join(wrap("Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all.", 60)))

fig.tight_layout()
title.set_y(1.05)
fig.subplots_adjust(top=0.8)

fig.savefig("1.png")

enter image description here

Ответ 2

Один из способов сделать это - просто изменить размер шрифта заголовка:

import pylab as plt

plt.rcParams["axes.titlesize"] = 8

myTitle = "Some really really long long long title I really really need - and just can't - just can't - make it any - simply any - shorter - at all."
plt.title(myTitle)
plt.show()

enter image description here

В ответе, который вы связываете, есть несколько других хороших решений, которые включают добавление новых строк. Существует даже автоматическое решение, которое изменяется на основе цифры!

Ответ 3

Я предпочел адаптировать решение @Adobe следующим образом:

plt.title("First Title\n%s" % "\n".join(wrap("Second Title", width=60)))