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

如何在Matplotlib极坐标图中设置径向步长为6并自动适配范围

解决Matplotlib极坐标图径向刻度步长为6且自动适配数据的问题

我明白你需要批量绘制极坐标图,要求径向刻度固定步长为6,同时自动适配每个图的数据范围,手动设置范围显然不现实。咱们来修改你的代码,完美解决这个问题:

关键思路

  1. 首先获取当前数据集的最大值,然后计算出刚好大于等于这个最大值的、6的倍数作为径向轴的上限
  2. 基于这个上限生成步长为6的刻度列表
  3. 使用ax.set_rticks()来设置径向刻度(注意极坐标里径向刻度对应的是rticks,不是yticks,这也是你之前set_yticks无效的原因)

修改后的完整代码

import matplotlib
import os
import matplotlib.pyplot as plt
import math  # 用于向上取整

#Define arrays
def processDir(file, output, title):
    angles=list()
    values=list()
    lines = [line.rstrip('\n') for line in open(file)]
    for line in lines:
        # Iterate lines
        stringElement = str.split(line, " ") # Split elements
        angle = int(stringElement[0])
        value = float(stringElement[1])
        angles.append((angle/360)*2*math.pi)  # 用math.pi更准确
        values.append(value)
    
    # 计算数据最大值,生成步长为6的刻度
    max_val = max(values)
    # 计算刚好大于等于max_val的6的倍数
    upper_limit = math.ceil(max_val / 6) * 6
    # 生成从0到upper_limit,步长6的刻度
    rticks = list(range(0, int(upper_limit) + 1, 6))
    
    # Plot values
    ax = plt.subplot(111, projection='polar')
    plt.polar(angles, values, label=title, color="darkviolet")
    # 设置径向刻度
    ax.set_rticks(rticks)
    # 可选:如果希望径向轴严格到upper_limit,可以设置rmax,否则matplotlib会自动适配
    ax.set_rmax(upper_limit)
    
    ax.text(-0.4, 0.3, 'Test\nTest', horizontalalignment = 'center', verticalalignment = 'center', transform = ax.transAxes)
    ax.legend(bbox_to_anchor=(0., 1.1, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0., frameon=False)
    ax.grid(True)
    ax.figure.set_size_inches(8, 5)
    plt.savefig(output)
    plt.close()  # 批量绘图时记得关闭图,避免内存泄漏
    # plt.show()  # 批量绘图时建议注释掉,否则会弹出很多窗口

folder = "mapje"
for filename in os.listdir(folder):
    if filename.endswith(".txt"):
        inputPath = os.path.join(folder, filename)
        bareName = os.path.splitext(filename)[0]
        outputPath = os.path.join(folder, bareName+".pdf")
        title = "dB waarde terts " + bareName
        processDir(inputPath, outputPath, title)

代码解释

  • 用math.ceil(max_val /6)*6确保我们得到的上限是刚好能覆盖数据最大值的6的倍数,比如你的测试数据最大值是57.5,计算后得到60,刻度就是0,6,12,...,60
  • 极坐标的径向刻度要用ax.set_rticks(),而不是set_yticks(),这是你之前尝试失败的核心原因
  • 批量绘图时加上plt.close()可以避免内存占用过高,同时建议注释掉plt.show(),否则会逐个弹出窗口影响效率
  • 用math.pi代替手动写的3.1415926,计算角度更准确

这样修改后,每个极坐标图都会自动根据自己的数据生成步长为6的径向刻度,完全不需要手动设置范围,完美适配批量绘图的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:21:47