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

如何使用Python的matplotlib和numpy创建圆形频率直方图(玫瑰图)

玫瑰图(圆形频率直方图)实现方案

以下代码基于Python3的matplotlib和numpy库实现,可生成0~360度区间、每10度为一个统计区间的玫瑰图,解决区间重叠、半径与频率值不匹配的问题:

import numpy as np
import matplotlib.pyplot as plt

# 读取单列存储的频率数据
with open('frequencies.txt', 'r', encoding='utf-8') as f:
    freq_list = [int(line.strip()) for line in f if line.strip()]
freq_array = np.array(freq_list)

# 配置区间参数:单区间宽度为10度,转换为弧度计算
bin_width_deg = 10
bin_width_rad = np.deg2rad(bin_width_deg)
# 计算每个区间的中心角度,用于对齐柱状图位置
theta = np.deg2rad(np.arange(0, 360, bin_width_deg)) + bin_width_rad / 2

# 创建极坐标画布
plt.figure(figsize=(8, 8))
ax = plt.subplot(111, polar=True)

# 绘制玫瑰图,半径直接对应频率值,宽度匹配10度区间
ax.bar(
    x=theta,
    height=freq_array,
    width=bin_width_rad,
    edgecolor='white',  # 相邻区间添加白色边框增强区分度
    alpha=0.8
)

# 调整极坐标方向符合常规使用习惯:0度在正北,角度顺时针递增
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
# 设置刻度每30度显示一次
ax.set_xticks(np.deg2rad(np.arange(0, 360, 30)))

plt.show()

核心逻辑说明

  • 区间宽度直接设置为10度对应的弧度值,避免默认宽度导致的区间重叠
  • 柱状图高度参数直接传入读取的频率数组,保证半径与频率值完全对应
  • 调整了极坐标的默认0度位置和增长方向,符合角度统计的通用认知

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:57:02