求助生成含定义域限制与指示箭头的饼图(chart_pie)
实现带定义域限制与箭头标识的饼图
以下以Matplotlib和Plotly为例,提供具体实现方案:
Matplotlib 实现示例
1. 基础依赖安装
pip install matplotlib numpy
2. 完整代码
import matplotlib.pyplot as plt import numpy as np # 示例数据 labels = ['定义域A', '定义域B', '定义域C', '定义域D'] sizes = [15, 30, 45, 10] colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99'] # 定义定义域的角度范围(例:下半圆,90°到270°) domain_theta1 = 90 domain_theta2 = 270 # 绘制带定义域限制的饼图 wedges, texts, autotexts = plt.pie( sizes, labels=labels, colors=colors, startangle=90, wedgeprops={'theta1': domain_theta1, 'theta2': domain_theta2}, # 核心:限制显示角度范围 autopct='%1.1f%%', pctdistance=0.8 ) # 添加指向定义域的箭头标注 plt.annotate( '定义域范围', xy=(0.5, -0.8), # 箭头指向的扇形区域位置 xytext=(0.8, -1.2), # 标注文本位置 arrowprops=dict(facecolor='black', shrink=0.05, arrowstyle='->'), fontsize=12 ) # 保证饼图为圆形,调整布局 plt.axis('equal') plt.title('带定义域限制与箭头的饼图') plt.show()
关键功能说明
- 定义域限制:通过
wedgeprops参数的theta1和theta2,指定饼图的起始/结束角度,只渲染该范围内的扇形区域。 - 箭头标识:使用
plt.annotate()函数,通过xy设置箭头指向坐标,xytext设置文本位置,arrowprops定义箭头样式,实现指向定义域的标注。
Plotly 实现示例(交互式)
1. 基础依赖安装
pip install plotly
2. 完整代码
import plotly.graph_objects as go # 示例数据 labels = ['定义域A', '定义域B', '定义域C', '定义域D'] sizes = [15, 30, 45, 10] colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99'] # 创建带定义域限制的饼图 fig = go.Figure(data=[go.Pie( labels=labels, values=sizes, marker_colors=colors, startangle=90, endangle=270, # 核心:限制饼图的结束角度,实现定义域范围 textinfo='percent+label', textposition='inside' )]) # 添加箭头标注 fig.add_annotation( x=0.5, y=-0.8, xref="paper", yref="paper", text="定义域范围", showarrow=True, arrowhead=2, ax=0, ay=-40, font=dict(size=12) ) # 设置图表标题 fig.update_layout(title_text='交互式带定义域限制的饼图') fig.show()
关键功能说明
- 定义域限制:通过
startangle和endangle参数直接指定饼图的角度范围,仅展示该区间内的内容。 - 箭头标识:使用
add_annotation()函数,配置showarrow=True启用箭头,通过ax/ay调整箭头偏移,实现指向标注。
内容的提问来源于stack exchange,提问作者islem habibi
相关产品推荐
相关产品推荐

