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

ChartJS多折线图点无法连接问题求助(Laravel+API场景)

问题

用Laravel结合ChartJS开发折线图,从API拉取数据时遇到异常:多折线共存时,部分折线的点无法连接成线。比如红色折线显示正常,但绿色折线只显示孤立的点,删掉红色折线后绿色折线就能正常连线。另一个包含姓名、年龄、薪资的API用完全相同的blade图表代码却能正常运行。


Blade 代码

<div class="graph">
        <form>
            @csrf
        <label for="startdate">Start Date</label>
        <input type="date" name="startdate" id="startdate"/>
        <label for="enddate">End Date</label>
        <input type="date" name="enddate" id="enddate"/>
        <input type="submit" value="Shfaq vlerat">
        </form>
    <div class="card text-center m-5">
        <div class="card-header">
            <h2>Currency Outlay</h2>
        </div>
        <canvas id="myChart" ></canvas>
    </div>

<script>

    var albanianLek = [], americanDollar = [], euro = [], britishPound = [], created_date = []

    async function dummyChart() {
        await getData()

        const ctx = document.getElementById('myChart').getContext('2d');

        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: created_date,
                datasets: [{
                    label: 'ALL',
                    borderColor: 'rgb(255, 0, 0)',
                    data: albanianLek
                },
                    {
                        label: 'GBP',
                        borderColor: 'rgb(0, 153, 153)',
                        data: britishPound
                    },
                    {
                        label: 'USD',
                        borderColor: 'rgb(0, 153, 0)',
                        data: americanDollar
                    },
                    {
                        label: 'EUR',
                        borderColor: 'rgb(0, 0, 255)',
                        data: euro
                    },
                ]
            },
            options: {
                tooltips: {
                    mode: 'index'
                }
            }
        })}

    dummyChart()

    async function getData() {
        const apiUrl = "http://127.0.0.1:8000/api/outlay";

        const response = await fetch(apiUrl)
        const barChatData = await response.json()

        const ALL = barChatData[0].map((item) => {
            return item.value_with_currencies.ALL;
        })
        const USD = barChatData[0].map((item) => {
            return item.value_with_currencies.USD;
        })
        const EUR = barChatData[0].map((item) => {
            return item.value_with_currencies.EUR;
        })
        const GBP = barChatData[0].map((item) => {
            return item.value_with_currencies.GBP;
        })
        const date = barChatData[0].map((item) => {
            return item.updated_at;
        })

        albanianLek = ALL
        britishPound = GBP
        americanDollar = USD
        euro = EUR
        created_date = date
    }
</script>

api.php 代码

Route::get('outlay/{startdate?}/{enddate?}',[GetValuesController::class,'getOutlays']);

Controller 代码

function getOutlays(Request $request)
{
    $startdate = $request->startdate;
    $enddate = $request->enddate;

    if($startdate == null && $enddate == null)
    {
        $values = response()->json([OutlayResource::collection(Outlay::where("status", Status::CONFIRMED_BY_EMPLOYEE)->orderBy('updated_at', 'asc')->get())], 200);
    }
    else
    {
        $values = response()->json([OutlayResource::collection(Outlay::where("status", Status::CONFIRMED_BY_EMPLOYEE)->whereBetween("updated_at", [$startdate, $enddate])->orderBy('updated_at', 'asc')->get())], 200);
    }

    return $values;
}

图表效果

  • 异常效果:
    异常图表效果
  • 正常参考效果:
    正常图表效果

原因分析与解决方法

核心原因

ChartJS绘制折线时,两个常见问题会导致折线断开:

  1. 数据数组中存在null、undefined或非数值类型的元素,ChartJS会跳过这些点,导致折线中断;
  2. 不同数据集的数值量级差异过大,Y轴自动适配大数值后,小量级的折线会被压缩到几乎贴在X轴上,看起来像是没连线。

具体修复步骤

  1. 处理空值/非数值数据
    在前端map数据时,把空值或非数值转为0,确保每个数据点都是有效数值:
const USD = barChatData[0].map((item) => {
    // 空值或非数值转为0,保证折线连续
    return item.value_with_currencies.USD ?? 0;
})
  1. 解决数值量级差异问题
    给不同量级的数据集配置独立Y轴,避免互相影响:
// 修改datasets配置,给每个数据集指定yAxisID
datasets: [{
    label: 'ALL',
    borderColor: 'rgb(255, 0, 0)',
    data: albanianLek,
    yAxisID: 'y'
},
{
    label: 'USD',
    borderColor: 'rgb(0, 153, 0)',
    data: americanDollar,
    yAxisID: 'y1'
}]

// 在options中添加多Y轴配置
options: {
    scales: {
        y: {
            type: 'linear',
            display: true,
            position: 'left',
        },
        y1: {
            type: 'linear',
            display: true,
            position: 'right',
            grid: {
                drawOnChartArea: false,
            },
        }
    },
    tooltips: {
        mode: 'index'
    }
}
  1. 校验数据长度一致性
    确保每个数据集的长度和created_date的标签长度完全一致,避免因数据不匹配导致的绘制异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:18:21