如何将csv导入chart.js?

时间:2017-01-05 16:19:54

标签: csv charts chart.js papaparse import-csv

我一直在寻找这个解决方案,但似乎无法找到它。 chart.js支持这个吗?

我试图用papaparse解析数据,但由于我的知识有限,我无法找到解决方案。

3 个答案:

答案 0 :(得分:0)

我也经常需要做这样的事情。以下是有关create a chart with Chart.js from a CSV file如何直接从CSV文件中解释如何使用Chart.js创建图表的链接。

该用例说明了如何使用Flex.io Web服务将CSV文件转换为JSON(完全披露:我是Flex.io的高级前端开发人员)。

如果您希望查看运作中的用例,请点击JsFiddle

function getRandomColor() {
  var letters = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

$.ajax({
  type: 'post',
  url: 'https://www.flex.io/api/v1/pipes/flexio-chart-js-csv-to-json/run?stream=0',
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Bearer nmgzsqppgwqbvkfhjdjd');
  },
  data: $('form').serialize(),
  dataType: "json",
  success: function(content) {
    // render the JSON result from from the Flex.io pipe
    $("#flexio-result-data").text(JSON.stringify(content, null, 2))

    var first_item = _.get(content, '[0]', {})

    var column_labels = _.map(_.omit(first_item, ['os']), function(val, key) {
      if (key != 'os')
        return key
    })

    // use Lodash to reformat the JSON for use with Chart.js
    var datasets = _.map(content, function(item) {
      // use the 'os' column as our label
      var item_label = _.get(item, 'os', 'Not Found')

      // create an array of number values from each item's JSON object
      var item_values = _.map(_.omit(item, ['os']), function(val) {
        return parseFloat(val)
      })

      return {
        label: item_label,
        data: item_values,
        backgroundColor: getRandomColor()
      }
    })

    var chart_data = {
      labels: column_labels,
      datasets: datasets
    }

    // render the JSON result after mapping the data with Lodash
    $("#chart-data").text(JSON.stringify(chart_data, null, 2))

    // render the chart using Chart.js
    var ctx = document.getElementById("canvas").getContext("2d");
    window.my_chart = new Chart(ctx, {
      type: 'bar',
      data: chart_data,
      options: {
        responsive: true,
        legend: {
          position: 'top'
        },
        title: {
          display: true,
          text: 'Use Flex.io to Create a Chart With Chart.js Directly From a CSV File'
        }
      }
    });
  }
});

如果您有任何问题,请随意浏览用例并告诉我。

答案 1 :(得分:0)

有一个Chart.js插件chartjs-plugin-datasource,可轻松从CSV文件加载数据。

假设您有一个CSV文件,如下所示,并且已另存为public class UserParcelable : Java.Lang.Object, IParcelable { public UserParcelable() { } public int DescribeContents() { throw new NotImplementedException(); } public void WriteToParcel(Parcel dest, [GeneratedEnum] ParcelableWriteFlags flags) { throw new NotImplementedException(); } } 与HTML文件位于同一目录中。

sample-dataset.csv

在页面中包含Chart.js和chartjs-plugin-datasource:

,January,February,March,April,May,June,July
Temperature,7,7,10,15,20,23,26
Precipitation,8.1,14.9,41.0,31.4,42.6,57.5,36.0

然后,在脚本中指定<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource@0.1.0"></script> <canvas id="myChart"></canvas> 。默认情况下,CSV文件中的每一行都将映射到一个数据集,并且第一列和第一行将分别被视为数据集标签和索引标签。您还可以使用选项自定义如何解析CSV数据。

sample-dataset.csv

答案 2 :(得分:0)

这是我的解决方案,对我来说效果很好。我有一个这样的 CSV 文件:

country,population
China,1415046
India,1354052
United States,326767
Indonesia,266795
Brazil,210868
...

我想用我的数据集绘制条形图,y-axispopulationx-axiscountry
这是我的 HTML 文件的 body

 <body>
    <canvas id="myChart" width="100" height="100"></canvas>
    <script>
      // Load the dataset
      d3.csv("data.csv").then(makeChart);

      // Plot the data with Chart.js
      function makeChart(countries) {
        var countryLabels = countries.map(function (d) {
          return d.country;
        });
        var populationData = countries.map(function (d) {
          return d.population;
        });

        var chart = new Chart("myChart", {
          type: "bar",
          data: {
            labels: countryLabels,
            datasets: [
              {
                data: populationData 
              }
            ]
          }
        });
      }
    </script>
</body>

结果: enter image description here

你可以用 Codesandbox 试试。

相关问题