问题
For the code given below to create a donut chart from matplotlib official page(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()
I understand that the line
ax.annotate(recipe[i],xy(x,y),xytext(1.35*np.sign(x),1.4*y),horizontalalignment=horizontalalignment, **kw)
defines tha annotation, however I am not able to understand how to control the size of the annotation text.
Any help would be appreciated. Thanks in advance.
回答1:
You're correct in identifying that line as defining the annotation. From the documentation for ax.annotate, we can see that extra keywords are passed to a matplotlib.Text object. This object accepts a fontsize
kwarg, which can be one of {size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
.
For example:
ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
horizontalalignment=horizontalalignment,
fontsize=8, **kw)
Output:
Or with larger text:
ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
horizontalalignment=horizontalalignment,
fontsize=16, **kw)
Output:
来源:https://stackoverflow.com/questions/59153347/matplotlib-pie-donut-chart-annotation-text-size