You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib 3.9.2极坐标图方形边框无法移除的问题求助

解决Matplotlib 3.9.2极坐标环形图方形边框问题

我从同事处获取了一段通过柱状图转换绘制三类数据占比极坐标环形图的代码,该代码在Matplotlib 3.7.0版本中正常显示,但升级到3.9.2后,环形图表周围始终存在一个无法去除的方形边框。我尝试了多种方法(如关闭轴、清除脊柱、隐藏刻度等)均无效,希望找到一行代码级的修复方案。

原代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from math import pi

data = [15, 20, 12]
fig, ax = plt.subplots(figsize=(6, 6), facecolor='white')
ax = plt.subplot(projection='polar', frameon=False)

startangle = 90
colors = ['#005a85', '#4c4c4d', '#048543']
colors_bg = ['#818589', '#818589', '#818589']

xs = [(i * pi *2)/ 100 for i in data]
xs_bg = [(i * pi *2)/ 100 for i in [100,100,100]]
ys = [-0.2, 1, 2.2]
left = (startangle * pi * 6)/ 360            #this is to control where the bar starts

# plot bars and points at the end to make them round
for i, x in enumerate(xs_bg):#draw the background grey circles
    ax.barh(ys[i], x, left=left, height=0.4, color=colors_bg[i])

for i, x in enumerate(xs):   
    ax.barh(ys[i], x, left=left, height=0.4, color=colors[i])
    ax.scatter(x+left, ys[i], s=60, color=colors[i], zorder=2)
    ax.scatter(left, ys[i]-0.01, s=60, color=colors[i], zorder=2)

plt.ylim(-4, 4)

# clear ticks, grids, spines
plt.xticks([])
plt.yticks([])
ax.spines.clear()

# Other attempts to remove the frame, none worked
ax.axis("off")
ax.set_axis_off()
ax.grid(False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.gca().get_xaxis().set_visible(False)
plt.gca().get_yaxis().set_visible(False)

plt.tight_layout()
plt.show()

问题现象

图表中的环形数据展示区域外侧,存在一圈明显的方形边框,与Matplotlib 3.7.0版本的无框显示效果不符。

修复方案

问题根源在于代码中先创建了一个默认的笛卡尔坐标系轴,随后又创建极坐标轴覆盖了变量ax,但原笛卡尔轴仍保留在画布中,这就是方形边框的来源。只需修改轴的创建方式,直接生成极坐标轴即可解决:

将原代码开头的两行:

fig, ax = plt.subplots(figsize=(6, 6), facecolor='white')
ax = plt.subplot(projection='polar', frameon=False)

替换为:

fig, ax = plt.subplots(figsize=(6, 6), facecolor='white', subplot_kw={'projection': 'polar', 'frameon': False})

这样就不会生成多余的笛卡尔轴,方形边框自然消失。

内容的提问来源于stack exchange,提问作者sguo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 16:40:21