如何在 Matplotlib 中将饼图中的 autopct 文本颜色更改为白色?

pythonserver side programmingprogramming更新于 2025/8/8 14:04:17

要将 Matplotlib 中饼图中的 autopct 文本颜色更改为白色,我们可以采取以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。
  • 列出 小时、活动 和 颜色 以绘制饼图。
  • 在制作饼图时,为数字标签列出 '.Text' 实例。
  • 迭代自动文本并将自动文本的颜色设置为白色。
  • 要显示图形,请使用 show() 方法。

示例

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

plt.figure()

hours = [8, 1, 11, 4]
activities = ['sleeping', 'exercise', 'studying', 'working']
colors = ["grey", "green", "orange", "blue"]
_, _, autotexts = plt.pie(hours, labels=activities, colors=colors, autopct="%.2f")

for ins in autotexts:
    ins.set_color('white')

plt.show()

输出


相关文章


有用资源