matplotlib的同一注释中的不同字体大小?
Posted
技术标签:
【中文标题】matplotlib的同一注释中的不同字体大小?【英文标题】:Different font sizes in the same annotation of matplotlib? 【发布时间】:2013-01-16 14:57:32 【问题描述】:我需要用几条数据线来注释一个 pylab 矩形 - 这些数据线的长度 不同。 通过 matplotlib 文档和谷歌搜索,我找不到一种方法来为注释的不同部分赋予不同的大小。
下面的 sn-p 演示了这个问题:
import pylab
from matplotlib.patches import Rectangle
pylab.rcParams['verbose.level'] = 'debug-annoying'
def draw_rectangle(lower, upper, entry):
ax = pylab.subplot(111)
r = Rectangle( lower, upper[0]-lower[0], upper[1] - lower[1],
edgecolor='k')
ax.add_patch(r)
textRank = str(entry['rank'])
textTeamName = entry['teamName']
textSubmissionDate = entry['submissionDate']
text = textRank + "\n" + textTeamName + "\n" + textSubmissionDate
ax.add_artist(r)
rx, ry = r.get_xy()
cx = rx + r.get_width()/2.0
cy = ry + r.get_height()/2.0
ax.annotate(text, (cx, cy), color='w', weight='bold', ha='center', va='center', size=14)
if __name__ == '__main__':
entry = 'rank': 22, 'submissionDate': '12/21/2012 4:58:45 AM', 'teamName': 'A very very very very very very very very very very long name'
lower = [0,0]
upper = [1,1]
draw_rectangle(lower, upper, entry)
pylab.show()
例如,有没有办法让“teamName”的字体大小与“rank”的字体大小不同的注释?
另一个问题是我找不到字体大小与缩放相关的方法: 我正在创建一个树形图,即 pylab 窗口中填充了不同大小的矩形。如果我想为不同的矩形创建注释,长数据需要非常小(保持在各自矩形的边界内)。但是,我希望长数据行的字体大小在放大时增长。
【问题讨论】:
【参考方案1】:首先制作您的绘图,然后使用ax.annotate
,迭代您的 x 坐标、y 坐标、标签和字体大小。
import matplotlib.pyplot as plt
X = [1,2,3,4,5]
Y = [1,1,1,1,1]
labels = 'ABCDE'
sizes = [10, 15, 20, 25, 30]
fig, ax = plt.subplots()
ax.scatter(X, Y)
for x, y, label, size in zip(X, Y, labels, sizes):
ax.annotate(label, (x, y), fontsize=size)
plt.show()
【讨论】:
【参考方案2】:我找不到创建具有不同字体的注释的方法,因此我将创建一个辅助函数,该函数将计算用于注释每一行的字体粗细,以及相关的 (cx, cy), 然后多次调用 ax.annotate。
【讨论】:
你愿意分享吗? :-)以上是关于matplotlib的同一注释中的不同字体大小?的主要内容,如果未能解决你的问题,请参考以下文章
Python使用matplotlib函数subplot可视化多个不同颜色的折线图为多个子图添加总标题(main title)自定义设置主标题字体类型字体大小字体颜色等
Python使用matplotlib函数subplot可视化多个不同颜色的折线图为每一个子图添加子图小标题(subtitle)使用family参数自定义子标题字体类型字体大小