Matplotlib:饼图下半部分标签反向旋转与标签位置调整求助
环形饼图标签调整解决方案
修改要点
- 将Parameter 1移至顶部:在
ax.pie()中添加startangle=90参数,让饼图从顶部(90度方向)开始绘制。 - 下半部分标签反向显示:给
plot_curved_text函数增加reverse参数,对下半部分(第7-12个参数)的标签反转文本路径,确保文字正向可读。
完整修改代码
import numpy as np import matplotlib.pyplot as plt from matplotlib.textpath import TextPath from matplotlib.patches import PathPatch fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0, 0, 1, 1], aspect=1) size = 0.1 params = [ "Parameter 1", "Parameter 2","Parameter 3","Parameter 4","Parameter 5","Parameter 6", "Parameter 7","Parameter 8","Parameter 9","Parameter 10","Parameter 11","Parameter 12" ] # 调整startangle=90,让第一个饼块从顶部开始 ax.pie(np.ones(12), radius=1, colors=["#F5F5F5"] * len(params), wedgeprops=dict(width=size, edgecolor="w"), startangle=90) # 改进的曲文本绘制函数,支持反向显示 def plot_curved_text(text, angle, radius=1, scale=0.005, reverse=False): "credits: Nicolas P. Rougier" path = TextPath((0, 0), text, size=10) path.vertices.flags.writeable = True V = path.vertices xmin, xmax = V[:, 0].min(), V[:, 0].max() ymin, ymax = V[:, 1].min(), V[:, 1].max() V -= (xmin + xmax) / 2, (ymin + ymax) / 2 V *= scale # 反向处理下半部分标签 if reverse: V[:, 0] = -V[:, 0] for i in range(len(V)): a = angle - V[i, 0] V[i, 0] = (radius + V[i, 1]) * np.cos(a) V[i, 1] = (radius + V[i, 1]) * np.sin(a) patch = PathPatch(path, facecolor="k", linewidth=0) ax.add_artist(patch) # 遍历参数,区分上下部分处理标签 for idx, (val, label) in enumerate(zip( np.linspace(0.5, 11.5, 12), params )): # 计算当前饼块的角度(对应startangle=90的调整) angle = val * 2 * np.pi / 12 - np.pi/2 # 减去π/2对应startangle的偏移 # 下半部分(第7-12个参数,索引6-11)开启反向 reverse = idx >= 6 plot_curved_text(label, angle, 1 - 0.5 * size, reverse=reverse) plt.show()
代码说明
- startangle参数:设置为90后,饼图的第一个分块(对应Parameter1)会从顶部竖直方向开始绘制,直接解决标签位置问题。
- reverse参数处理:当下半部分标签绘制时,反转文本的x轴坐标,同时配合角度偏移,确保文字以正向朝向外侧,避免出现倒置情况。
内容的提问来源于stack exchange,提问作者slothfulwave612
相关产品推荐
相关产品推荐

