2014-09-26 128 views
2
import matplotlib.pyplot as plt 
from textwrap import wrap 

x_list = [11, 3, 6, 5] 
label_list = ["red colour", "blue colour", "green colour", "back colour"] 

title = "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?" 

newtitle = '\n'.join(wrap(title, width=50)) # wrap the long title so that it won't get cropped. 

# here if I print `newtitle` first then "text below the main title" gets convert into italics 
newtitle = "%s\n$%s$"%(newtitle, 'text\ below\ the\ main\ title') 
# but If I print `newtitle` after the secondary text it doesn't convert into italics 
newtitle = "%s\n$%s$"%('text\ below\ the\ main\ title', newtitle) # comment this line for 1st effect 

plt.figure(figsize=(7,6), dpi=100) 
plt.axis("equal") 
plt.subplots_adjust(left=0.1, right=0.8, top=0.7) 
plt.rc("font", size=10) 
explode = [0.03, 0, 0, 0] 

plt.pie(x_list, labels=label_list, explode=explode, autopct="%1.1f%%", startangle=90) 
plt.title(newtitle, size=12) 

plt.savefig('test.png') 

所以我的主要問題是 -標題在matplotlib斜體不工作

輔助文本來首次以正常字體,然後主標題(newtitle)在此之後以斜體/ Light字體來(容貌漂亮)。

newtitle = "%s\n$%s$"%('text\ below\ the\ main\ title', newtitle)

我們能做到這一點,而無需使用$標誌?

+0

你檢查這一點:http://stackoverflow.com/a/4056853/832621? – 2014-09-26 08:48:19

+0

@SaulloCastro:是的..但它的代碼太多了。我想知道這是否可以巧妙/很快完成。 – xyz 2014-09-26 08:49:12

回答

1

這是預期的結果?

enter image description here

它可以使用mathtext一個快速和骯髒的方式來完成的,但你必須有$剝落各線,如:

newtitle = '\n'.join(['$%s$'%item for item in wrap(title, width=50)]).replace(' ', '\ ') 
newtitle = "%s\n%s"%('text\ below\ the\ main\ title', newtitle) 

但我認爲更好看的方法是將這兩個標題分開。您可以使用suptitle作爲上面的一個,也可以使用text,然後您可以單獨控制其屬性。例如: -

plt.pie(x_list, labels=label_list, explode=explode, autopct="%1.1f%%", startangle=90) 
plt.title('\n'.join(wrap(title, width=50)), size=12, style='italic') 
plt.suptitle('some title', y=0.85, x=0.45) #y and x needed as you have adjusted the subplot size already. 

enter image description here