I am attempting to build a dynamic report using d3.js and I am currently sourcing the report with data from a .csv file. However, an example I'm using uses "#csv"
from a static csv list:
var parsedCSV = d3.csv.parse(d3.select("#csv").text());
The "#csv"
is static code written above it in the .html as follows:
<pre id="csv">col a, col b, col c
0,0,0
30,30,30
70,70,70
0,30,70
70,30,0</pre>
I want to replace the "#csv"
portion with myCSVfile.csv
, which is a .csv reported generated every hour for my report (which is a webpage dashboard). The myCSVfile.csv
file will sit next to this index.html
file in an IIS environment when I deploy it.
Here is the rest of the code I am using for concept. Credits to Gerado Furtado for being very helpful with this example:
<!DOCTYPE html>
<html>
<head>
<style>
pre {
display: none;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td,th {
padding: 10px;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<pre id="csv">foo,bar,baz
32,55,67
12,34,99
11,21,32
11,65,76
99,14,23</pre>
<script type="text/javascript">
var parsedCSV = d3.csv.parse(d3.select("#csv").text());
var colorScale = d3.scale.threshold()
.domain([30, 70])
.range(["red", "yellow", "green"]);
var body = d3.select("body");
var headers = Object.keys(parsedCSV[0]);
var table = body.append('table')
var thead = table.append('thead')
var tbody = table.append('tbody');
var head = thead.selectAll('th')
.data(headers)
.enter()
.append('th')
.text(function(d) {
return d;
});
var rows = tbody.selectAll('tr')
.data(parsedCSV)
.enter()
.append('tr');
var cells = rows.selectAll('td')
.data(function(d) {
return Object.values(d);
})
.enter()
.append('td')
.style("background-color", function(d) {
return colorScale(d);
})
.text(function(d) {
return d;
});
</script>
</body>
</html>
When I attempt to switch the #csv to my actual .csv file, nothing happens. I am having trouble identifying the error.
The reason I used a <pre>
element (in my answer to your last question) to store the data and d3.csvParse
(or d3.csv.parse
in v3) to read it is simple: I like using S.O. snippet to show the demos, but unlike Plunker, I cannot save a CSV file in the snippet. If I gave you the wrong impression that this is a good practice, I apologize: it's not.
That being said, for using d3.csv, you have to pass the URL of your file and the callback. So, in your case, it would be:
d3.csv("myCSVfile.csv", function(parsedCSV){
//your whole code here, from 'var colorScale' to 'var cells'
});
Please notice that, using "myCSVfile.csv", the script will look for a CSV in its same directory. If the file's directory is different, change the path accordingly.