Importing a CSV file into Highcharts for data visualization

I am in the process of plotting Csv column data using highcharts. Instead of utilizing the following code snippet:

$.get('5.csv', function(data)

I am interested in inputting a local desktop Csv file with the help of:

function handleFileSelect(evt) {
var files = evt.target.files; // FileList object

The current Javascript code that I have is as follows :

var options = {
chart: {
    renderTo: 'container',
    defaultSeriesType: 'line'
},
title: {
    text: 'Test'
},
xAxis: {
    categories: []
},
yAxis: {
    title: {
        text: 'Units',

    }
},
series: []
};

// $.get('5.csv', function(data) {

var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);

    var lines = txt.split('\n');
    var c = [], d = [];
    $.each(lines, function(lineNo, line) {
            if(lineNo > 0 ){
                var items = line.split(','); 
                var strTemp = items[0];
                c = [parseFloat(items[0]), parseFloat(items[1])];
                d.push(c);
                console.log(c);
            }
    });


    options.xAxis.categories = c;
    options.series = [{
            data: d
    }];
    chart = new Highcharts.Chart(options);
});

What would be the best approach to accomplish this task? I aim to upload a Csv file from a local desktop machine. How can I connect the File Reader upload of the file to highcharts for plotting, rather than relying on $.get(5.csv', function(data) { ? Or should I consider using jquery-csv (https://github.com/evanplaice/jquery-csv). I understand there might be browser security concerns. My Csv file consists of 3 columns with a single-line header - column 1 represents the x-axis, column 2 signifies the y-axis, and column 3 will depict the error bar (which I have not implemented yet):

Q,I,E
0.009,2.40E-01,5.67E-02
0.011,2.13E-01,3.83E-02
0.013,2.82E-01,2.28E-02

and so on ....

Answer №1

File API Integration for Improved Functionality

function handleFiles(files) {
    var chart;
    options = {
            chart: {
                zoomType: 'x',
                renderTo: 'container',
                type: 'line',
                zoomType: 'x'

            },
            title: {
                text: ''
            },
            subtitle: {
                text: '' 
            },
            xAxis: {
                type: 'linear',
                minorTickInterval: 0.1,
                title: {
                    text: 'Q'}
            },
            yAxis: {
                type: 'linear',
                minorTickInterval: 0.1,
                title: {
                    text: 'I(Intensity)'
                },
            },
            tooltip: {
                shared: true
            },
            legend: {
                enabled: true
            },
            plotOptions: {
                area: {
                    fillColor: {
                        linearGradient: [0, 0, 0, 300],
                        stops: [
                            [0,      Highcharts.getOptions().colors[0]],
                            [0, 'rgba(2,0,0,0)']
                        ]
                    },
                    lineWidth: 1,
                    marker: {
                        enabled: false,
                        states: {
                            hover: {
                                enabled: true,
                                radius: 5
                            }
                        }
                    },
                    shadow: false,
                    states: {
                        hover: {
                            lineWidth: 1
                        }
                    }
                }
            },
            series: [{
                name: 'Data Series'}]
    };



var selectedFile = files[0]
var fileReader = new FileReader();
fileReader.onload = function (e) {

data = e.target.result;
    var lines = data.split("\n");
    var coordinates = [], values = [], errors = [];
    $.each(lines, function(lineNo, line) {
            if(lineNo > 0 ){
                var items = line.split(','); 
                var strTemp = items[0];
                errors = parseFloat(items[2])
                pointA = parseFloat(items[0])
                pointB = parseFloat(items[1])
                minRange = (pointB - (errors/2))
                maxRange = pointB + ((errors/2))
                coordinates = [pointA , pointB];
                var rangeValues = [], errorValues = [];
                rangeValues = [minRange, maxRange]
                errorValues.push(rangeValues);

                values.push(coordinates);

                console.log(coordinates);
                console.log(rangeValues);
            }
    });

    options.xAxis.categories = coordinates.name;
    lineWidth: 1
    options.series = [{
            data: values,
            type: 'scatter'
    }, {
        name: 'Standard Deviation',
        type: 'errorbar',
        color: 'black',
        data : errorValues }
];
    $("#Linear").click(function(){
        $('#container').highcharts().yAxis[0].update({ type: 'linear'});
    });

    $("#Logarithmic").click(function(){
        $('#container').highcharts().yAxis[0].update({ type: 'logarithmic'});
    });

    $("#Guinier").click(function(){
        $('#container').highcharts().yAxis[0].update({ data: Math.log(values)});
        options.xAxis.categories = coordinates.name;
        lineWidth: 1
        options.series = [{
            data: values
    }]
    });

  chart = new Highcharts.Chart(options);
}

    fileReader.readAsText(selectedFile)
    var output = document.getElementById("fileOutput")

};

Answer №2

For security purposes, it is not recommended to directly load a file on the client-side.

To achieve this task, you should utilize the HTML5 File API, which will prompt the user to select the file through a file dialog.

If you are considering using jquery-csv for this purpose, you can refer to the following example for guidance:

In my opinion, using jquery-csv to parse the data is the way to go as writing a CSV parser from scratch can be quite challenging due to various tricky scenarios.

Source: I am the creator of jquery-csv

Alternatively, if jquery-csv does not meet your requirements, you may want to explore PapaParse as an excellent alternative.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I incorporate dynamic data to draw and showcase graphs on my website using PHP?

I am currently working on a project that requires displaying a graph showing the profit of users per day. Currently, I have implemented code to display a static graph on my page. <script type="text/javascript" src="https://www.google.com/jsapi">< ...

How can I establish a breakpoint on an HTML element?

For instance, I have a button element with the click event attached to an ID in XXX.js file (the actual file name is unknown), and there are several .js files in the project. How can I debug the button click if I don't know where the function for it i ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...

What is the best way to input keys into the currently selected element?

During my experimentation, I discovered that several modals and dropdowns in my tests open with their input boxes automatically focused. I found a way to verify if an element is in focus, but I'm wondering if there's a quicker method to input ke ...

The HTML5 video will continue playing indefinitely as long as its readyState remains at 4

In my efforts to develop a personalized HTML5 video player that can handle live streaming, recording of live streams, and playing regular video files, I have run into an issue with creating a custom seeking bar. To achieve this, I implemented the following ...

Verify the content of each file in a bulk upload before transferring them to the server

I am facing an issue with a form that has 3 separate file input fields. I need to validate their MIME types individually before uploading them to the server. The first two should only allow MP3 files, while the last one should only allow JPEG files. Is th ...

Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one. I am l ...

Having Difficulty Applying a Background Color to a Class in Bulk

I am working on a unique HTML canvas for pixel art, which is created using a table made up of various divs all sharing the "pixel" class. I want to add a clear button that can reset the entire canvas, but changing the background color of each individual di ...

Aligning a div with absolute positioning vertically

There are two elements positioned side by side: an input field and a div. The div is absolutely positioned inside a relative element and placed to the right of the input. The input field has a fixed height, while the height of the div depends on its conte ...

Issue with Vue 3: Composition API does not support Array of refs

Check out the code snippet below. <template> <div v-for="item in arr" :key="item">{{ item }}</div> </template> <script> import { ref } from "vue"; export default { name: "TestArr", ...

Using Vue to fetch JSON data with Axios

When trying to retrieve user data from a MongoDB in JSON format using axios.get within a Vue.js application, my aim is to visualize this data by iterating through all user objects in the users array. The issue I'm facing is that each character is trea ...

What is the reason behind HTML IDs being displayed as global variables in a web browser?

Browser exposes HTML IDs as global variables. <span id="someid" class="clsname1 clsname2 clsname3"></span> If you have the above HTML snippet, you can access a global variable called someid. You can interact with it in your console like this: ...

jqGrid doesn't refresh after making an AJAX request

I'm encountering an issue when trying to refresh a jqgrid. Despite attempting various solutions, I have yet to find one that works. My goal is to refresh the grid after receiving JSON data from the server side. Below is the code snippet showcasing how ...

Possible rewrite: "Unable to use jQuery to add elements to data fetched through AJAX requests."

I am looking to add a button to copy code inside every div that has a class starting with language. The code is functioning properly, however, after attempting to retrieve data from the database using Ajax, the button no longer appears in the div as it did ...

Steps to create an instance method that only accepts the name of another instance method

I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them? Let's t ...

Creating an image from the contents of a div is necessary in order to visually

I am looking to develop a software that can: receive text input from the user and place it in a specific div allow users to adjust font, color, and size based on their preferences enable image uploads as background save all customizations and send them v ...

Is it possible to set a variable to a specific value inside a callback function in JavaScript?

Currently, I'm working on developing a Chrome extension that focuses on conversions. However, I've hit a roadblock when it comes to retrieving data from storage. Below is the code snippet I'm currently using: var conversionFactor = 1; ...

What is the best way to access a specific value within an array that contains a mix of objects and arrays

Currently, I am attempting to extract particular values from an array that is nested within another array. Specifically, I am utilizing the Spotify Web API to retrieve the track names from a playlist. Here is an illustration of how the nested array is str ...

Infrastructural setup for multiplayer games using Socket.io

var connectionHandler = function(socket) { var player = null; socket.on('login', function(data) { player = { data: okeyServer.playerJoin(data), socket: socket }; socket.emit('welcome'); }); socket. ...

Having trouble with jQuery validation: Seeking clarification on the error

I have implemented some validations on a basic login page and added jQuery validation upon button click. However, the code is not functioning as expected. I have checked the console for errors but none were displayed. Here is the code for your review: ...