2012-04-27 46 views
11

有一個similar question - 但我不能讓解決方案建議在那裏工作。我如何適合長頭銜?

下面是一個例子情節與長標題:

#!/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' 

,如果我fig.tight_layout()取代(matplotlib.pyplot).tight_layout()它給:

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

所以我的問題是 - 我如何適應情節的標題?

+1

'tight_layout'僅在近一matplotlib的釋放。你使用什麼版本?我認爲'tight_layout'在1.1中增加了,儘管它可能是1.0。 – 2012-04-27 13:35:02

+0

我的是'1.0.1'。 – Adobe 2012-04-27 13:39:25

+0

@Joe Kington:可能你是對的:再現你的[answer](http://stackoverflow.com/a/9604442/788700)給出了同樣的錯誤。我正在下載最新的源代碼。 – Adobe 2012-04-27 13:48:35

回答

35

這裏就是我終於用:

#!/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

5

一種方式做到這一點是簡單地更改標題的字體大小:

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

在回答您鏈接是涉及添加換行符其他幾個很好的解決方案。甚至有一個automatic solution,根據這個數字調整大小!

+0

這很酷。 +1 – Adobe 2012-04-27 13:58:33

+1

@Adobe用於定製matplotlib的go-to頁面在這裏:http://matplotlib.sourceforge.net/users/customizing.html,但它可以幫助你知道你在找什麼! – Hooked 2012-04-27 14:20:05

+0

這可行,但它是一個不好的解決方案。在你的例子中,標題的字體甚至比刻度標籤更小。這會使標題在出版物或演示文稿中很難閱讀。 – gerrit 2016-01-26 16:31:38