Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

matplotlib - How do I fit long title?

There's a similar question - but I can't make the solution proposed there work.

Here's an example plot with a long title:

#!/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("
".join(textwrap.wrap(myTitle, 80)))

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

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

it gives a

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

and if I replace (matplotlib.pyplot).tight_layout() with fig.tight_layout() it gives:

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

So my question is - how do I fit the title to the plot?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's what I've finally used:

#!/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("
".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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...