有没有一种简便的方法可以将CSV文件中的值打印到JS图表中而不进行转换?

时间:2018-08-10 04:02:18

标签: javascript json csv charts chart.js

我在JSFIDDLE上看到了以下代码:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Chart.js chart from a CSV</title>


    <style>
      html, body {
        font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        height: 100%;
        margin: 0;
      }
      /* Same as .flex-auto in Tachyons except without the 'auto' flex-basis */
      .flex-fill {
        flex: 1 1;
        min-width: 0; /* 1 */
        min-height: 0; /* 1 */
      }
    </style>
  </head>
  <body>

    <div id="top"></div>

    <div id="app" class="tc">
      <canvas id="canvas"></canvas>
    </div>

    

    <script src="https://cdn.jsdelivr.net/npm/flexio-sdk-js@latest"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
    <script>
      var renderChart = function(data) {
        var chart_data = formatDataForChart(data)
        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 firectly from a CSV file'
            }
          }
        })
      }
      var formatDataForChart = function(content) {
        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
        }
        return chart_data
      }
      var getRandomColor = function() {
        var letters = '0123456789ABCDEF'.split('')
        var color = '#'
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)]
        }
        return color
      }
      Flexio.setup('rryrjgqhvtdttzzsjpjr')
      Flexio.pipe()
        // request the content of the URL that is specified
        .request('https://raw.githubusercontent.com/flexiodata/examples/master/demo-chartjs-from-csv/source-data/phone-market-share.csv')
        // convert the above CSV-formatted text into JSON
        .convert('csv','json')
        .run(function(err, response) {
          var data = JSON.parse(response.text)
          renderChart(data)
        })
    </script>
  </body>
</html>

这是一个使用CSV数据的图表,但在使用CSV数据之前将其转换为JSON。我希望制作一个图表,以图表形式显示来自url文件的CSV数据,而无需进行额外的转换。现在,我是Javascript的新手,因此我希望能获得一些帮助,并非常感谢。谢谢

2 个答案:

答案 0 :(得分:1)

有一个Chart.js插件chartjs-plugin-datasource,可轻松从CSV文件加载数据。默认情况下,CSV文件中的每一行都将映射到一个数据集,并且第一列和第一行将分别被视为数据集标签和索引标签。您还可以使用选项自定义如何解析CSV数据。

<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>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataSource],
    options: {
        daatasource: {
            url: 'phone-market-share.csv'
        }
    }
});

答案 1 :(得分:0)

我的意思是,如果您有csv字符串,我们假设变量为csv

OS,2009,2010,2011,2012,2013,2014,2015,2016,2017
Android,1.6,9.6,36.4,56.9,74.4,80.8,78.8,84.1,86.1
iOS,10.5,15.4,16.9,22.5,18.2,15.3,17.9,14.8,13.7
Microsoft,10.2,6.8,2.6,1.9,2.9,2.7,2.5,0.7,0.1
RIM,20.6,19.7,13,6.8,3,0.6,0.4,0.2,0
Symbian,48.8,44.2,27.7,8.5,0.6,0.2,0.1,0,0

先用换行符将其分隔,然后再用逗号将其分隔。

const array = csv.split('\n').map(col => col.split(','));