Python中关于Matplotlib饼状图代码的问题,谢谢大家!

import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(13,8), subplot_kw=dict(aspect="equal"))

recipe = ["USA:99 (44.39%)", "UK:28 (12.56%)", "Germany:33 (14.80%)", "France:15 (6.726%)", "FRG:4 (1.794%)", "Switzerland:6 (2.691%)", "Sweden:8 (3.587%)", "Others:30 (13.45%)"] ingredients=['USA','UK','Germany','France','FRG','Switzerland','Sweden','Others']

data = [99, 28, 33, 15, 4, 6,8,30] colors=['#1F77B4','#FF7F0E','#2CA02C','yellow','#D62728','lawngreen','#8C564B','cyan'] wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=30,colors=colors)

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.35np.sign(x), 1.4y), horizontalalignment=horizontalalignment, **kw)

ax.legend(wedges, ingredients, bbox_to_anchor=(1, 0, 0.5, 1)) plt.show()

代码如上,现在只想让注释框中的国家(英文)放在各自框的上面并居中,数字仍保留在框里,不知道如何修改代码?请大家指导!谢谢大家!(先发帖,一会上图,还不会贴图--~


Python中关于Matplotlib饼状图代码的问题,谢谢大家!

6 回复
import matplotlib.pyplot as plt

# 数据准备
labels = ['苹果', '香蕉', '橙子', '梨子', '葡萄']
sizes = [30, 25, 20, 15, 10]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0']

# 创建饼图
fig, ax = plt.subplots(figsize=(8, 6))

# 绘制饼图
wedges, texts, autotexts = ax.pie(
    sizes,
    labels=labels,
    colors=colors,
    autopct='%1.1f%%',
    startangle=90,
    explode=(0.05, 0, 0, 0, 0),  # 突出显示第一块
    shadow=True
)

# 设置文本样式
for text in texts:
    text.set_fontsize(12)
for autotext in autotexts:
    autotext.set_color('white')
    autotext.set_fontweight('bold')

# 设置标题
ax.set_title('水果销售比例', fontsize=16, fontweight='bold')

# 确保饼图是圆形
ax.axis('equal')

# 添加图例
ax.legend(wedges, labels, title="水果种类", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))

plt.tight_layout()
plt.show()

这个代码创建了一个完整的饼图,包含数据标签、百分比显示、颜色设置、突出效果和阴影。关键参数说明:

  • autopct:控制百分比显示格式
  • startangle:设置起始角度
  • explode:让某块饼突出显示
  • shadow:添加阴影效果

用这个模板改数据就行。

既然都在右上角给了图例,我觉得直接去掉国家名也可以:dog:。

谢谢你!目前在撰写论文,因为打印出来是黑白的,所以考虑这个因素,添加上国家名称。

这样阿,我觉得可以图片二次加工一下( ps )就好啦 23333。
或者我觉得你可以拿这个调一下参数,换一下参数位置避免遮挡之后的效果可能比你那个好看一丢丢。
https://echarts.baidu.com/examples/editor.html?c=pie-nest

回到顶部