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

Streamlit中雷达图(Spider Graph)无法显示问题求助

解决Streamlit中Matplotlib雷达图不显示的问题

问题原因

  • 缺少Streamlit渲染函数:Jupyter会自动渲染Matplotlib绘图对象,但Streamlit需要显式调用st.pyplot()展示生成的图表,原代码未执行此步骤。
  • 固定布局限制:原代码用plt.subplot(3,3,row+1)固定3行3列布局,若簇数量超出9个会报错,布局逻辑不够灵活。
  • 依赖模块缺失:代码使用pi但未显式导入math模块,Jupyter可能隐含导入,但Streamlit运行时会出现未定义错误。
  • 全局绘图对象混乱:直接在函数中创建子图,未明确管理Matplotlib的Figure和Axes对象,易导致渲染异常。

修复后的完整代码

import matplotlib.pyplot as plt
import math
import streamlit as st
import pandas as pd

# 数据处理部分
Spider_kmeans = df[['Cluster_kmeans_Label','Age','Annual Income (k$)','Spending Score (1-100)','Sex (100=Male)']]
# 简化groupby语法,避免重复指定分组列
Spider_kmeans = Spider_kmeans.groupby('Cluster_kmeans_Label').mean().reset_index()

def make_spider_kmeans(ax, row, title, color):
    # 获取特征列名
    categories = list(Spider_kmeans)[1:]
    N = len(categories)

    # 计算雷达图角度
    angles = [n / float(N) * 2 * math.pi for n in range(N)]
    angles += angles[:1]

    # 设置雷达图方向和偏移
    ax.set_theta_offset(math.pi / 2)
    ax.set_theta_direction(-1)

    # 设置x轴标签
    plt.xticks(angles[:-1], categories, color='black', fontfamily='serif', fontweight='light', size=8)

    # 设置y轴标签和范围
    ax.set_rlabel_position(0)
    plt.yticks([10,20,30,40,50,75,100], ["10","20","30","40","50","75","100"], color="grey", size=4)
    plt.ylim(0,100)

    # 获取当前簇的特征值并闭合雷达图
    values = Spider_kmeans.loc[row].drop('Cluster_kmeans_Label').values.flatten().tolist()
    values += values[:1]
    ax.plot(angles, values, color=color, linewidth=2, linestyle='solid')
    ax.fill(angles, values, color=color, alpha=0.4)

    # 设置子图标题
    ax.set_title(title, size=10, fontfamily='serif', fontweight='bold', y=1.2)

# Streamlit图表渲染部分
my_dpi = 96
cluster_count = len(Spider_kmeans.index)
# 动态计算子图行数(采用2列布局)
rows = (cluster_count + 1) // 2
# 创建Figure和Axes对象
fig, axes = plt.subplots(rows, 2, figsize=(1000/my_dpi, 1000/my_dpi), dpi=my_dpi, subplot_kw={'polar': True})
# 将Axes转为一维数组方便遍历
axes = axes.flatten()

# 循环生成每个簇的雷达图
for row in range(cluster_count):
    make_spider_kmeans(
        ax=axes[row],
        row=row,
        title=f'Cluster: {Spider_kmeans["Cluster_kmeans_Label"][row]}',
        color='#244747'
    )

# 隐藏多余的子图(当簇数量为奇数时)
for ax in axes[cluster_count:]:
    ax.axis('off')

plt.tight_layout()
# 关键:调用Streamlit的函数渲染Matplotlib图表
st.pyplot(fig)

核心修复点说明

  1. 添加st.pyplot(fig):这是Streamlit展示Matplotlib图表的必要步骤,必须将生成的Figure对象传入该函数。
  2. 动态子图布局:根据簇的数量自动计算子图行数,避免固定布局的限制,同时处理奇数数量簇的多余子图隐藏。
  3. 显式导入math模块:确保math.pi可以正常使用,避免运行时错误。
  4. 明确管理Axes对象:将Axes作为参数传入绘图函数,避免全局plt对象的混乱,提升代码可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:06:26