matplotlib同一个注解中的不同字体大小

问题描述 投票:0回答:3

我需要用几条数据线来注释一个 pylab 矩形——它们具有 不同 长度。 搜索 matplotlib 文档和谷歌搜索,我找不到给注释的不同部分提供不同大小的方法。

以下片段演示了问题:

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 窗口充满了不同大小的矩形。如果我想为不同的矩形创建注释,长数据需要非常小(以保持在各自矩形的边界内)。但是,我希望长数据行的字体大小在放大时grow

python matplotlib font-size treemap plot-annotations
3个回答
48
投票

先画图,然后使用

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()


4
投票

我找不到用不同字体创建注释的方法,所以我将创建一个辅助函数来计算注释的每一行使用的字体粗细,以及相关的(cx,cy),
和然后调用 ax.annotate 几次。


0
投票

Annotations 存储在

ax.texts
中,这是一个 Annotation 对象的列表。注释对象定义了一个
set_size()
方法,如果需要更改特定注释的字体大小 after 绘制,则可以调用该方法。

如果带有注释的图是使用外部库(如 scikit-learn、statsmodels 等)创建的,这将特别有用

import matplotlib.pyplot as plt

X, Y, labels = [1,2,3,4,5], [1]*5, 'ABCDE'
sizes = [10, 15, 20, 25, 30]

# scatter plot with annotations
plt.scatter(X, Y)
for x, y, label in zip(X, Y, labels):
    plt.annotate(label, (x, y))

# change annotation fontsizes
ax = plt.gca()
for a, size in zip(ax.texts, sizes):
    a.set_size(size)

© www.soinside.com 2019 - 2024. All rights reserved.