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

如何用MySQL数据填充饼图?解决x must be 1D报错问题

解决方法

cursor.fetchall()返回的列表中,每个元素都是单元素元组(格式类似[(18,), (22,), (25,)]),直接转numpy数组会得到二维结构,而plt.pie()要求输入一维数据,这就是报错的核心原因。

你可以按以下步骤处理:

  • 提取元组中的age值,生成一维列表:
    ages = [item[0] for item in res]
    
  • 直接用这个一维列表绘制饼图(转numpy数组可选,matplotlib支持直接传入列表):
    import matplotlib.pyplot as plt
    import numpy as np
    
    # 提取一维数据
    ages = [item[0] for item in res]
    # 转numpy数组(可选操作)
    ages_np = np.array(ages)
    # 绘制饼图
    plt.pie(ages_np)
    plt.show()
    

如果查询结果包含NULL值(对应Python中的None),建议先过滤无效数据:

ages = [item[0] for item in res if item[0] is not None]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:45:31