Dygraph加载光伏控制器CSV数据时触发Cannot read properties of undefined错误
Dygraph加载光伏控制器数据CSV时出现"Cannot read properties of undefined (reading 'push')"错误排查
使用Dygraph展示多SQLite数据库数据,通过Python脚本导出CSV供Dygraph使用。脚本处理其他数据库正常,但处理光伏控制器数据时触发错误,相同JS代码可加载其他CSV,且CSV在Excel/Google Docs中显示正常。
控制台错误信息
Uncaught TypeError: Cannot read properties of undefined (reading 'push') at Q.visibility (dygraph.min.js:4:26567) at Q.getPropertiesForSeries (dygraph.min.js:4:889) at o.generateLegendHTML (dygraph.min.js:5:13732) at o.deselect (dygraph.min.js:5:13159) at Q.cascadeEvents_ (dygraph.min.js:3:25191) at Q.clearSelection (dygraph.min.js:4:10470) at Q.mouseOut_ (dygraph.min.js:4:10406) at mouseOutHandler_ (dygraph.min.js:3:30272)
展示Dygraph的HTML/JS代码
<html><head> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.css" /> </head><body> <div class="container" style="display: flex; height: 350px;"> <div id="solar_chart" style="width: 50%; height:350px;"> </div> <div id="nrg_chart" style="flex-grow: 1; height:350px;"> </div> </div> <script type="text/javascript"> solchart = new Dygraph( document.getElementById('solar_chart'), "solarpwr.csv", { title: ['Solar Generation'], visibility: [true], axes: { x: { }, y: { drawGrid: false } } }); </script> </body></html>
生成CSV的Python代码
import csv import sqlite3 import pandas as pd conn = sqlite3.connect('/home/pi/restapi/database.db',detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) cursor = conn.cursor() cursor.execute("select battery_percentage, load_current, load_power, pv_current, pv_power, date from solarnrg;") with open('/var/www/html/solarpwr.csv', 'w',newline='') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow([i[0] for i in cursor.description]) csv_writer.writerows(cursor) conn.close() csv_data = pd.read_csv('/var/www/html/solarpwr.csv', usecols=[0,1,2,3,4,5]) col = csv_data.pop("date") csv_data.insert(0, col.name, col) csv_data.to_csv('/var/www/html/solarpwr.csv', index = False)
排查思路与解决方案
1. 修复Dygraph visibility配置不匹配问题
错误栈指向visibility方法,核心原因是配置的visibility数组长度与CSV中的数据系列数量不匹配:
- CSV包含5个数值数据系列(battery_percentage、load_current、load_power、pv_current、pv_power),但JS配置中
visibility仅设置了1个元素[true]。 - Dygraph内部会遍历每个数据系列匹配visibility配置,当找不到对应配置项时会导致变量未定义,触发
push错误。
修改JS配置,让visibility数组长度与数据系列数一致:
visibility: [true, true, true, true, true], // 5个元素对应5个数据系列,可按需将不需要显示的设为false
2. 验证CSV数据格式一致性
虽然CSV在Excel中正常,但需确认:
- 所有行的列数完全一致,无缺失列的行
- date列的时间格式符合Dygraph解析要求(如
YYYY-MM-DD HH:MM:SS等标准格式) - 数值列无非数值内容(如空字符串、异常字符)
3. 优化Python生成CSV的逻辑(可选)
当前代码先写入CSV再用pandas调整列顺序,可直接在SQL查询中指定date为第一列,减少IO操作并避免潜在格式问题:
# 调整SQL查询,将date放在第一列 cursor.execute("select date, battery_percentage, load_current, load_power, pv_current, pv_power from solarnrg;") # 移除后续pandas列调整代码
内容的提问来源于stack exchange,提问作者prupert
相关产品推荐
相关产品推荐

