Html plot graph from csv

I need to show a graph[piegraph and XYgraph] in HTML file. I have used some free tool created an image and I am trying to show this on HTML.

But, we need to place this image in shared folder or in a server to get accessed by HTML.Our client is not satisfied with both approaches.

Can some please let me know whether there is any way where I can pass data directly to html file. The data will be in csv file and it may contain some thousands of rows.

Thanks,

asked Aug 1, 2012 at 6:35

1

As an alternative you can also look at the Dojo Toolkit [//dojotoolkit.org/], its a Javascript toolkit with some really nice features including charting.

answered Aug 1, 2012 at 7:39

Rainer.RRainer.R

4482 silver badges8 bronze badges

With CanvasJS, we can easily create charts from CSV. Comma Separated Value [CSV] stores the tabular data in plain-text format with a separator between each column and new line between every row.

We will be using following CSV format in this example:

5,9
6,9
7,14
8,12
9,14
10,18
11,13
12,8
13,11
14,13

Here is the code for creating Charts from CSV. We will get CSV Data using AJAX call [jQuery] and convert the same to CanvasJS supported format [Please refer to Working with Data]. Then we will initialize a chart and pass the data to be rendered.

var dataPoints = [];

function getDataPointsFromCSV[csv] {
    var dataPoints = csvLines = points = [];
    csvLines = csv.split[/[\r?\n|\r|\n]+/];
        
    for [var i = 0; i < csvLines.length; i++]
        if [csvLines[i].length > 0] {
            points = csvLines[i].split[","];
            dataPoints.push[{ 
                x: parseFloat[points[0]], 
                y: parseFloat[points[1]] 		
	    }];
	}
    return dataPoints;
}
	 
$.get["//canvasjs.com/services/data/datapoints.php?xstart=5&ystart=10&length=10&type=csv", function[data] {
    var chart = new CanvasJS.Chart["chartContainer", {
        title: {
	    text: "Chart from CSV",
        },
        data: [{
	    type: "line",
	    dataPoints: getDataPointsFromCSV[data]
	}]
    }];
		
    chart.render[];

}];

Finalising

To summarize, in order to create a charts from CSV, we just need to parse the data to CanvasJS supported format and then pass the dataPoints to the chart.

Below is the compilation of final code.

Try it Yourself by Editing the Code below.


Requires intermediate knowledge of JavaScript

21 January 2019

In this tutorial I show you how to load a comma separated value [CSV] file and visualise it using Chart.js.

Click image to view interactive chart

Background

A CSV file is a text file that represents a table of data. Think of it as a text-based representation of a spreadsheet. Each line represents a row in the spreadsheet and each value is separated by a comma:

Name,Weeks,Gender
Steffi Graf,377,Female
Martina Navratilova,332,Female
Serena Williams,319,Female
Roger Federer,308,Male
etc.

The CSV data we’ll use is a list of tennis players containing the number of weeks they’ve spent at the top of the ATP [for men] and WTP [for women] rankings. The original dataset is from Tableau.

You’ll use D3 to load the CSV file and Chart.js to make the chart.

Getting started

You’ll use CodePen to make the chart because it’s easy to use and requires minimal set-up. If you prefer to develop locally you can export the project files from the pen. [You’ll also need to set up local webserver.]

In CodePen create a new pen then click on the cog in the JS panel.

Add Chart.js and D3 by adding the following URLs to the ‘Add External Scripts/Pens’ list:

  • //cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js
  • //cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js

Make a simple chart

You’ll start by creating a simple bar chart using Chart.js.

Add a element to the HTML:


This will act as a container for the chart.

Now add the following JavaScript [to CodePen’s JS panel]:

var chart = new Chart['chart', {
  type: 'horizontalBar',
  data: {
    labels: ['A', 'B', 'C'],
    datasets: [
      {
        data: [10, 20, 30]
      }
    ]
  }
}];

This uses Chart.js to create a horizontal bar chart.

In CodePen’s output panel you should see something like:

Load the csv file

You’ll use D3’s .csv[] function to request the CSV file. [The CSV file is hosted at //s3-us-west-2.amazonaws.com/s.cdpn.io/2814973/atp_wta.csv].

Add the following to the top of the JavaScript:

d3.csv['//s3-us-west-2.amazonaws.com/s.cdpn.io/2814973/atp_wta.csv']
  .then[makeChart];

function makeChart[players] {
  // players is an array of objects where each object represents a player
}

This does two things:

  • requests the CSV file
  • when the CSV arrives, converts it into an array and calls the function makeChart[]

The array will consist of objects, where each object represents a row in the CSV:

[
  {
    "Name": "Steffi Graf",
    "Weeks": "377",
    "Gender": "Female"
  },
  {
    "Name": "Martina Navratilova",
    "Weeks": "332",
    "Gender": "Female"
  },
  {
    "Name": "Serena Williams",
    "Weeks": "319",
    "Gender": "Female"
  },
  {
    "Name": "Roger Federer",
    "Weeks": "308",
    "Gender": "Male"
  },
  ...
]

The function makeChart[] is called after the array has been created and the array is passed in as the first parameter.

Add the CSV data to the chart

Move the chart code into makeChart[]. Your JavaScript is now:

d3.csv['//s3-us-west-2.amazonaws.com/s.cdpn.io/2814973/atp_wta.csv']
  .then[makeChart];

function makeChart[players] {
  var chart = new Chart['chart', {
    type: 'horizontalBar',
    data: {
      labels: ['A', 'B', 'C'],
      datasets: [
        {
          data: [10, 20, 30]
        }
      ]
    }
  }];
}

Note that makeChart’s first parameter is named players. This is the array of players.

Add the player names to the chart

The y-axis labels are set using the labels array [which is currently ['A', 'B', 'C']].

We’d like this to be an array of the player names. We can create this using JavaScript’s .map[] function.

Add the following to the beginning of makeChart[]:

var playerLabels = players.map[function[d] {return d.Name}];

The map[] function goes through each item of players and picks out the Name property. Thus playerLabels is an array like:

['Steffi Graf', 'Martina Navratilova', 'Serena Williams', ...]

Update labels value to playerLabels:

var chart = new Chart['chart', {
  type: 'horizontalBar',
  data: {
    labels: playerLabels,
    ...
  }
}];

You should now see the player names along the y-axis:

Add the weeks to the chart

The length of the bars are determined by the data array [which is currently [10, 20, 30]].

In a similar manner to the labels you’ll create an array of ‘weeks at number one’ using .map[]:

var weeksData = players.map[function[d] {return d.Weeks}];

Now update data’s value to weeksData:

...
  datasets: [
    {
      data: weeksData
    }
  ]
...

makeChart[] should now look like:

function makeChart[players] {
  var playerLabels = players.map[function[d] {return d.Name}];
  var weeksData = players.map[function[d] {return d.Weeks}];

  var chart = new Chart['chart', {
    type: 'horizontalBar',
    data: {
      labels: playerLabels,
      datasets: [
        {
          data: weeksData
        }
      ]
    }
  }];
}

Now you should be seeing a bar chart of the CSV data:

Loading your own data

You might like to load your own data into a Chart.js chart. If you know your way around a local webserver you can host the file locally and update the URL in the d3.csv[] call.

Otherwise you could host your CSV on CodePen and use its URL in the d3.csv[] call.

Summary

We loaded a CSV file into the browser using D3’s .csv[] function. This converts the CSV into an array of objects where each object represents a single player.

We then used JavaScript’s .map[] function to convert the array of objects into an array of player names and an array of weeks. We created a bar chart using Chart.js and used these two arrays to set the player labels and bar lengths.

The code

See the Pen Visualising a CSV file with Chart.js [basic] by Peter Cook [@createwithdata] on CodePen.


Here’s another version with additional styling:

See the Pen Visualising a CSV file with Chart.js by Peter Cook [@createwithdata] on CodePen.

How do I display data from CSV in HTML?

To display the data from CSV file to web browser, we will use fgetcsv[] function..
Comma Separated Value [CSV] is a text file containing data contents. ... .
fgetcsv[] Function: The fgetcsv[] function is used to parse a line from an open file, checking for CSV fields..
Execution Steps:.
Filename: code.php..
Output:.

Can you plot a graph in a csv file?

Import the date from the csv file into Excel. Go to the ribbon and click Insert. Choose the type of graph that you want to insert. On selecting a graph, a blank window will appear.

How do I convert CSV to graph?

How to Graph a CSV File in Excel.
Open your CSV file in MS Excel. Video of the Day..
Select the data cells you would like to graph by clicking on the corner cell and dragging the cursor to the far corner. Release the mouse button..
Create a chart by clicking on the "Chart Type" button on the Chart toolbar..

How do I embed a csv file in HTML?

Solution: You have to use jquery file for display csv files into the HTML..
import pandas as pd..
df = pd. read_csv['file. csv'].
html = df. to_html['converted_file. html'].

Chủ Đề