【问题标题】:Highcharts: create multiple series using JSON dataHighcharts:使用 JSON 数据创建多个系列
【发布时间】:2019-12-08 11:54:36
【问题描述】:

我正在尝试使用 JSON 数据创建 line, spline 图表。我想要多个系列,但我对如何做到这一点感到困惑。现在我可以用一个系列创建一个,但这个看起来也不正确。另外,我也没有看到传说。请帮助我如何解决这个问题。现在我只有starts 的代码。我也想completes 我的图表。我想让传说中的人说startcomplete

JSON 数据:

[
{
    "date": "2019-07-07",
    "starts": 42,
    "completes": 142
},
{
    "date": "2019-07-08",
    "starts": 2,
    "completes": 90
},
{
    "date": "2019-07-09",
    "starts": 28,
    "completes": 175
}
]

我的代码:

<div id="container"></div>

let theAPI = `the json file`

$.getJSON(theAPI, result => {
    let main_chart_data = [];

    result.forEach((d, i) => {
        let date_chart = new Date(d.date);
        main_chart_data.push([date_chart, d.starts, ]);
    });

    let main_chart_options = buildChart({
        chart_type: 'spline',
        height: 265
    });
    main_chart_options.legend.enabled = false;
    main_chart_options.lang = {
        'noData': 'There is currently no data available.'
    };
    main_chart_options.series = [{
        data: main_chart_data
    }];

    main_chart_options.tooltip = {
        formatter: function() {
            let tooltip = `
      <span style="font-weight:500;">${moment(this.x).format('MMM DD - ha')}</span>
      <br />
      <span>${addCommas(this.y)}</span>
    `;
            return tooltip;
        },
        useHTML: true
    }

    new Highcharts.chart('container', main_chart_options);

    let total_pvs = result.reduce((a, c) => {
        return a += c.starts;
    }, 0);

})

这是我现在的结果:

Spline - Highchart

【问题讨论】:

    标签: javascript jquery json highcharts spline


    【解决方案1】:

    您可以通过将 JSON 数据分成两个单独的系列来实现它,如下所示:

    [{
      "name": "starts",
      "data": [{
        "x": 1562457600000, // date in milliseconds
        "y": 42
      }, {
        "x": 1562544000000,
        "y": 2
      }, {
        "x": 1562630400000,
        "y": 28
      }]
    }, {
      "name": "completes",
      "data": [{
        "x": 1562457600000,
        "y": 142
      }, {
        "x": 1562544000000,
        "y": 90
      }, {
        "x": 1562630400000,
        "y": 175
      }]
    }]
    



    查看此演示,了解如何制作:

    【讨论】:

    • 感谢您的帮助!这行得通!是否也可以按月对这些数据进行分组?
    • 那是我像[ { "month": 6, "year": 2019, "starts": 21278998, "completes": 9309458 }, { "month": 7, "year": 2019, "starts": 38850115, "completes": 17790105 } ]这样设置JSON的时候
    • 嗨 Wojciech,我用了你的例子。我有一个关于某事的快速问题。这是我的小提琴:jsfiddle.net/rprak0605/kc9g5vrh。我想创建一个新系列,series5。我希望 series5 能够使用来自 json1 的 elem.starts 并将其除以来自 json2 的 elem.x。我希望series5 成为x: +new Date(elem.date), y: elem.starts/elem.x。有没有办法做到这一点?
    • 是的。检查这个例子:jsfiddle.net/BlackLabel/09nx3yot
    猜你喜欢
    • 1970-01-01
    • 2019-12-09
    • 2013-03-17
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多