Matplotlib pie/donut 图表注释文字大小

Matplotlib pie/donut chart annotation text size

对于下面给出的代码,从 matplotlib 官方页面创建圆环图(https://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/pie_and_donut_labels.html)


recipe = ["225 g flour",
          "90 g sugar",
          "1 egg",
          "60 g butter",
          "100 ml milk",
          "1/2 package of yeast"]

data = [225, 90, 50, 60, 100, 5]

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
          bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1)/2. + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                horizontalalignment=horizontalalignment, **kw)

ax.set_title("Matplotlib bakery: A donut")

plt.show()

我明白这行

ax.annotate(recipe[i],xy(x,y),xytext(1.35*np.sign(x),1.4*y),horizontalalignment=horizontalalignment, **kw)

定义了注释,但是我无法理解如何控制注释文本的大小。

您将该行标识为定义注释是正确的。来自 ax.annotate, we can see that extra keywords are passed to a matplotlib.Text 对象的文档。这个对象接受一个 fontsize kwarg,它可以是 {size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}.

之一

例如:

ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
            horizontalalignment=horizontalalignment,
            fontsize=8, **kw)

输出:

或更大的文字:

ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
            horizontalalignment=horizontalalignment,
            fontsize=16, **kw)

输出: