如何从一个js函数创建多个折线图

How to create multiple line charts from one js function

我正在尝试使用 Google line charts 作为我的烧瓶项目的一部分。但是我不只是想要一个图表,我有一个列表字典,每个列表都需要转换成折线图。但是,我对 js 没有多少经验,并且不确定为什么此时页面上没有显示任何内容。任何帮助将不胜感激

GraphData={
1:[['Col1','Col2'],[Row1,Row1],[Row2,Row2]],
2:[['Col1','Col2'],[Row1,Row1],[Row2,Row2],[Row3,Row3]}
3:[['Col1','Col2','Col3',[Row1,Row1,Row1],[Row2,Row2,Row2]}


#In the <head> area:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    {% for Vars in GraphData %}
        <script type="text/javascript">
            var Data =GraphData[Vars]
            google.charts.load('current', {'packages':['corechart']});
            google.charts.setOnLoadCallback(drawChart);
            function drawChart() {
            var data = google.visualization.arrayToDataTable(Datas}

            var options = {
                title: 'Graph Data',
                curveType: 'function',
                legend: { position: 'bottom' }
            };
            var chart = new google.visualization.LineChart(document.getElementById(Vars));

            chart.draw(data, options);
            }
        </script>
    {%endfor%}


and in the <body> section:

{% for Vars in GraphData %}
<div id={{Vars}} style="width: 900px; height: 500px"></div>
{% endfor %}



  • 首先将您的数据转换为 JSON,如果需要 parse it
  • 创建一个循环所有数据的函数processAllCharts()
  • 调用该函数作为回调:google.charts.setOnLoadCallback(processAllCharts);
  • 在该循环内将每条数据发送到 drawChart
  • 动态创建图表 DIV

const GraphData = [
  [
    ['Year', 'Foo', 'Bar'],
    ['2017', 2000, 400],
    ['2018', 660, 1120],
    ['2019', 1030, 540],
  ],
  [
    ['Year', 'Lorem', 'Ipsum'],
    ['2014', 780, 1400],
    ['2015', 998, 770],
    ['2016', 660, 1120],
  ],
  [
    ['Year', 'Dolor', 'Sit Amet'],
    ['2017', 660, 1120],
    ['2018', 1030, 540],
  ],
];

const EL_gAllCharts = document.querySelector("#gAllCharts");
const chartOptions = {
  title: 'Graph Data',
  curveType: 'function',
  legend: {
    position: 'bottom'
  }
};

function drawChart(data) {
  // Create charts
  const EL_gChart = document.createElement("div");
  EL_gChart.classList.add("gChart");
  gAllCharts.append(EL_gChart);

  const gData = google.visualization.arrayToDataTable(data)
  const chart = new google.visualization.LineChart(EL_gChart);
  chart.draw(gData, chartOptions);
}

function processAllCharts() {
  GraphData.forEach(drawChart);
}

google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(processAllCharts);
.gChart {
  height: 260px;
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="gAllCharts"></div>