n8n工作流自动化平台的实操:生成统计图的两种方式

1.成果展示

1.1n8n的工作流

牵涉节点:Postgres、Code、QuickChart、Edit Fields、HTTP Request

12.显示效果

2.实操过程

2.1节点说明

2.1.1Postgres节点:

注:将明细数据进行汇总。

2.1.2code节点:

注:将 查询的数据转换成QuickChart需要的格式,代码如下:

复制代码
let data = $input.all();
let rawData = data.map(item => item.json);

// 按年份分组数据
const groupedData = rawData.reduce((acc, item) => {
    if (!acc[item.nf]) acc[item.nf] = [];
    acc[item.nf].push({ month: item.yf, value: parseInt(item.sl) });
    return acc;
}, {});

// 构建完整的12个月份列表,作为 X 轴标签
const allMonths = Array.from({ length: 12 }, (_, i) => {
    const month = (i + 1).toString().padStart(2, '0'); // 01 - 12
    return month;
});

// 构建 QuickChart 需要的 chartData 格式
const chartData = {
    type: 'line',
    data: {
        labels: allMonths, // 使用完整12个月作为 X 轴
        datasets: Object.keys(groupedData).map(year => {
            // 补全缺失月份的数据为 null(图表上该点为空)
            const values = allMonths.map(month => {
                const found = groupedData[year].find(d => d.month === month);
                return found ? found.value : null;
            });

            return {
                label: `${year}年 事故起数`,
                data: values,
                borderColor: getRandomColor(),
                fill: false,
                pointRadius: values.map(v => v !== null ? 3 : 0), // 可选:隐藏空值点
            };
        })
    },
    options: {
        responsive: true,
        scales: {
            xAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: '月份'
                }
            }],
            yAxes: [{
                ticks: {
                    beginAtZero: true
                },
                scaleLabel: {
                    display: true,
                    labelString: '事故起数'
                }
            }]
        }
    }
};

// 随机颜色生成函数
function getRandomColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgba(${r},${g},${b},1)`;
}

return chartData;

2.1.3Edit Fields节点:

注:将json对象转换成字符串,主要图中的红框。

2.1.4HTTP Request节点:

注:通过https://quickchart.io/chart?width=650\&height=450\&c={{ $json.data }}实现图片的生成,图中红框部分。

通过 QuickChart节点,最后也是转成url地址。因此不能在无互联网的环境下生成图片,希望有缘人提供更好的思路。

2.1.5QuickChart节点:

注:生成单曲线,单柱状图,通过 QuickChart节点没有问题,如果有上传多条曲线,则无法实现,只能通过https://quickchart.io/chart?width=650\&height=450\&c={{ $json.data }}方式实现。

相关推荐
2022.11.7始学前端5 小时前
第二十二课 专属你的小说智能问答助手
工作流·coze
小妖同学学AI7 小时前
完全免费,5分钟拥有属于自己的n8n服务器
n8n
长不大的蜡笔小新1 天前
n8n--自动化网站内容抓取与知识库构建工作流
自动化·n8n
长不大的蜡笔小新1 天前
n8n--智能新闻简报自动化工作流
自动化·n8n
skyjilygao2 天前
n8n整合ffmpeg
ffmpeg·视频编辑·n8n
hhzz3 天前
Activiti7工作流(五)流程操作
java·activiti·工作流引擎·工作流
2022.11.7始学前端3 天前
n8n第十三节 三个节点测试技巧
运维·服务器·n8n
Jeking2173 天前
初探新一代workflow编辑器unione flow editor:企业级流程设计的高效解决方案
编辑器·流程图·workflow·工作流·flow editor·unione cloud
2022.11.7始学前端4 天前
n8n第十二节 《科技早报》自动化工作流(下):筛选新闻生图并推到企微
n8n
xrl20125 天前
ruoyi-vue2前端集成DMN规则引擎
前端·规则引擎·工作流·dmn