gpt4 book ai didi

javascript - 解析 CSV,然后使用数据构建 Highcharts 条形图

转载 作者:行者123 更新时间:2023-11-28 01:14:04 24 4
gpt4 key购买 nike

我想创建一个条形图可视化IN JS FIDDLE,为每个类别的消费者可视化“Q1/18 (TTM) Annual Guest Value”和“Days Between 1st and 2nd Visits”是:['1', '2', .....'29+']。条形图应如下所示(图例涵盖了第一个类别,但我会解决这个问题):

enter image description here

我假设数据已经存在于 CSV 中,如下所示:

enter image description here

我有一个允许用户导入 CSV 文件的界面。它在这里:

// The event listener for the file upload 
document.getElementById('txtFileUpload').addEventListener('change', upload, false);

// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
var isCompatible = false;
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCompatible = true;
}

return isCompatible;
}

function upload(evt) {
if (!browserSupportFileUpload()) {
alert('The File APIs are not fully supported in this browser!');
} else {
var data = null;
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csvData = event.target.result; //alert(csvData);
var data2 = csvData.split("\n"); //alert(data2);
var i;
for (i = 0; i < data2.length; ++i) {
// here's the data row separated by commas
alert(i+': '+data2[i]);
// call your ajax and submit this one row
// now wait for response
// if not error:
// advance progress bar, and number converted, etc in modal
// else:
// show error message
}

if (data2 && data2.length > 0) {
alert('Imported -' + data2.length + '- rows successfully!');
} else {
alert('No data to import!');
}
};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
}
<h1>File Upload Test</h1>
<p>
<div id="dvImportSegments" class="fileupload ">
<fieldset>
<legend>Select the CSV file to upload</legend>
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />
</fieldset>
</div>
</p>

然后,我使用 .get() 引入变量 csvData(来自上面代码中的一个函数),然后我将使用函数 parseCSVData 解析它(该函数在下面编写)。然后,我将制作数据的条形图。这是我这部分的代码:

$.get(csvData, function (csvFile) { //retrieve csvData from other function above

var data = parseCSVData(csvFile);


//create the chart

Highcharts.chart('container', {
chart: {
type: 'bar'
},

title: {
text: null,
align: 'center',
verticalAlign: 'bottom',
},
xAxis: {
categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11-17', '18-28', '29+'],

title: {
text: 'Visits Per Customer (TTM)'
},
},
yAxis: {
min: 0,
gridLineWidth: 0,
minorGridLineWidth: 0,

title: {
text: 'Average Return Rate Overall: 64 Days',
y: 10
},

labels: {
overflow: 'justify'

}
},

tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.0f} </b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
}
}
},
legend: {

layout: 'horizontal',
align: 'right',
verticalAlign: 'top',
x: -25,
y: 5,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),

shadow: true

},
credits: {
enabled: false
},
series: [{
name: 'Q1 / 18 (TTM) Annual Guest Value',
//data: 2nd column of CSV file
color: 'grey',
// label color
dataLabels: {
style: {
color: 'grey'

}
}
}, {
name: 'Days Between 1st and 2nd Visits',
//data: 3rd Column of CSV file
color: 'green',
// label color
dataLabels: {
style: {
color: 'green'
}
}
}]
})

})


function parseCSVData (csvFile){

//empty array for storing the chart data
var guestvalue_and_visits = []; //2nd and 3rd column extraction

var lines = csvFile.split("\n");

$.each(lines, function (lineNumber, line){
if(lineNumber != 0) { //skipping header lines
var fields = line.split(",");
var a = parseFloat(fields[1]); // this is guest value
var b = parseFloat(fields[2]); //this is days between visit
guestvalue_and_visits.push([a , b]);
}
})
return guestvalue_and_visits.reverse();
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>

我的问题是:

我需要解析的数据的正确形式是什么?是 var data2 = csvData.split("\n") 还是 var csvData = event.target.result?

我是否在 .get() 中正确引入了变量 csvData(或 data2,如果这是正确的)?我不是 Javascript 专家,但我很确定例如变量 csvData 是 reader.onload = function(event){} 的本地变量,所以我会以某种方式需要访问这个局部变量。我如何将其正确带入 .get()?简单地写 .get(csvData, function (csvFile){ 可以吗?

此外,如果您查看“系列”下的“数据”属性,我将其留空,因为我不知道如何将来自 guestvalue_and_visits 变量的数据导入 Highcharts 代码。 (我做了 guestvalue_and_visits.push([a , b] 因为这是 Highcharts 接受的形式)。我想从数据结构中提取 'a' 和 'b' 部分并将它们放在它们对应的 'data' 属性中 '系列”。我该怎么做?

最后但并非最不重要的一点是,将所有内容放在一起,我如何让界面首先允许用户上传 CSV 文件,然后在上传时,界面将变为 Highcharts 条形图?我需要编写某种代码来执行此操作吗?

最佳答案

What is the right form of the data that I need to parse? Is it var data2 = csvData.split("\n") OR is it var csvData = event.target.result?

在您的情况下,我建议您在 CSV 字符串解析器中分离类别和系列数据,并返回包含数据的两个不同系列,就像这样:

var parseCSV = function(csv) {
var lines = csv.split("\n").map(line => line.split(",")) // split string to lines
var categories = []
var series = [{
name: 'Q1 / 18 (TTM) Annual Guest Value',
color: 'grey',
data: [],
dataLabels: {
style: {
color: 'grey'

}
}
}, {
name: 'Days Between 1st and 2nd Visits',
color: 'green',
data: [],
dataLabels: {
style: {
color: 'green'
}
}
}]
// Parse every line of csv file.
lines.forEach((line, i) => {
if (i !== 0) {
var cat = line[0].slice(1, -1)
var p1 = parseFloat(line[1])
var p2 = parseFloat(line[2])

categories.push(cat)
series[0].data.push(p1)
series[1].data.push(p2)
}
})
// return the object with categories and series
return {
categories: categories,
series: series
}
}

然后只需分配类别和系列:

var parsedCSV = parseCSV(csv)

Highcharts.chart('container', {
xAxis: {
categories: parsedCSV.categories
},
series: parsedCSV.series
})

Did I bring in the variable csvData (or data2 if this is the right one) in correctly in .get()? I am not an expert in Javascript but I am pretty sure that for instance the variable csvData is local to reader.onload = function(event){} so I would somehow need to access this local variable. How would I bring this correctly into .get()? Would simply writing .get(csvData, function (csvFile){ be okay?

我没有看到你的整个元素结构,但是是的,csvDatadata2 变量范围仅限于 reader.onload因此,除此事件函数外,您不能在任何地方调用 get()

Last but not least, bringing everything together how would I allow the interface to FIRST allow the user to upload a CSV file and THEN when it is uploaded, the interface will change to the Highcharts bar chart? Is there some sort of code I need to write to do this?

其实我觉得生成图表的过程应该是这样的:

  1. 生成一个空图表(或带有一些初始数据)
  2. 从文件中获取 CSV
  3. 解析你得到的 CSV
  4. 解析后,只需使用 Chart.update() 方法用新的 categories 和整个 series 对象更新图表。

API 引用: https://api.highcharts.com/class-reference/Highcharts.Chart#update

以正确方式解析数据的实例: http://jsfiddle.net/db0vsgmh/

关于javascript - 解析 CSV,然后使用数据构建 Highcharts 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com