Giving graphs a subtitle in matplotlib

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

I want to give my graph a title in big 18pt font, then a subtitle below it in smaller 10pt font. How can I do this in matplotlib? It appears the title() function only takes one single string with a single fontsize attribute. There has to be a way to do this, but how?

回答1:

I don't think there is anything built-in, but you can do it by leaving more space above your axes and using figtext:

axes([.1,.1,.8,.7]) figtext(.5,.9,'Foo Bar', fontsize=18, ha='center') figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center') 

ha is short for horizontalalignment.



回答2:

What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different fontsize arguments). Hope that helps!



回答3:

Although this doesn't give you the flexibility associated with multiple font sizes, adding a newline character to your pyplot.title() string can be a simple solution;

plt.title('Really Important Plot\nThis is why it is important') 


回答4:

This is a pandas code example that implements Floris van Vugt's answer (Dec 20, 2010). He said:

>What I do is use the title() function for the subtitle and the suptitle() for the >main title (they can take different fontsize arguments). Hope that helps!

import pandas as pd import matplotlib.pyplot as plt  d = {'series a' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),       'series b' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d)  title_string = "This is the title" subtitle_string = "This is the subtitle"  plt.figure() df.plot(kind='bar') plt.suptitle(title_string, y=1.05, fontsize=18) plt.title(subtitle_string, fontsize=10) 

Note: I could not comment on that answer because I'm new to stackoverflow.



回答5:

Just use TeX ! This works :

title(r"""\Huge{Big title !} \newline \tiny{Small subtitle !}""") 

EDIT: To enable TeX processing, you need to add the "usetex = True" line to matplotlib parameters:

fig_size = [12.,7.5] params = {'axes.labelsize': 8,       'text.fontsize':   6,       'legend.fontsize': 7,       'xtick.labelsize': 6,       'ytick.labelsize': 6,       'text.usetex': True,       # <-- There        'figure.figsize': fig_size,       } rcParams.update(params) 

I guess you also need a working TeX distribution on your computer. All details are given at this page:

http://matplotlib.org/users/usetex.html



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!