Matplotlib注释文本的字体(不是大小)

时间:2018-07-06 20:03:26

标签: python-3.x matplotlib

在matplotlib网站上浏览后,我发现了一个饼图的示例代码,该饼图在自定义和功能方面具有完美的属性。但是,我想更改字体(而不是大小)。我无法找到如何对您在此处看到的注释执行此操作...

enter image description here

如果我可以通过名称指定字体(例如“ Helvetica”或“ Times_New_Roman”),而不是在matplotlib中更改字体的其他方式,那就更好了。

这是上面图片的代码...

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

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(xycoords='data', textcoords='data', 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()

请注意,我对在实际程序中将特定于标签文本的代码行放置在何处也感到困惑。

谢谢...

1 个答案:

答案 0 :(得分:1)

要更改字体,可以在注释函数中添加参数族

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

有更多可用的字体样式。您可以在Matplotlib文档中阅读有关它的更多信息。 https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.annotate https://matplotlib.org/2.0.2/users/text_props.html