D3 lets us add graphics to a front-end web app easily.
Vue is a popular front end web framework.
They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.
csvParseRows
We can use the csvParseRows
method to parse CSV strings into an array of objects.
For example, we can write:
import React, { useEffect } from "react";
import * as d3 from "d3";
const string = `2011,10\n2012,20\n2013,30\n`;
export default function App() {
useEffect(() => {
const data = d3.csvParseRows(string, function ([year, population]) {
return {
year: new Date(+year, 0, 1),
population
};
});
console.log(data);
}, []);
return <div className="App"></div>;
}
We call csvParseRows
with the CSV strings as the first argument.
The callback has the parsed entry and we can return what we want from it.
csvFormat
The csvFormat
method formats the CSV rows and columns.
For instance, we can write:
import React, { useEffect } from "react";
import * as d3 from "d3";
const data = [
{ year: 2011, population: 10 },
{ year: 2012, population: 20 },
{ year: 2013, population: 30 }
];
export default function App() {
useEffect(() => {
const string = d3.csvFormat(data, ["year", "population"]);
console.log(string);
}, []);
return <div className="App"></div>;
}
We pass in an array of objects as the first argument.
Then we pass in an array of strings with the column names.
And then we get the value of string
, which is the CSV string. Its value is:
year,population
2011,10
2012,20
2013,30
tsvParse
The tsvParse
method lets us parse tab-separated strings.
For instance, we can write:
import React, { useEffect } from "react";
import * as d3 from "d3";
const string = `year\tpopulation\n2011\t10\n2012\t20\n2013\t30\n`;
export default function App() {
useEffect(() => {
const data = d3.tsvParse(string, function ({ year, population }) {
return {
year: new Date(+year, 0, 1),
population
};
});
console.log(data);
}, []);
return <div className="App"></div>;
}
We have a tab-separated string and call tsvParse
with it.
Then on the callback, we destructure the year
and population
properties from the parsed entry in the parameter.
And we return the object to return what we want.
tsvParseRows
The tsvParseRows
method lets us parse the tab-separated string rows without the headings.
For example, we can write:
import React, { useEffect } from "react";
import * as d3 from "d3";
const string = `2011t10n2012t20n2013t30n`;
export default function App() {
useEffect(() => {
const data = d3.tsvParseRows(string, function ([year, population]) {
return {
year: new Date(+year, 0, 1),
population
};
});
console.log(data);
}, []);
return <div className="App"></div>;
}
We pass in a string without the headings.
Then we call tsvParseRows
with the string and the callback that has the properties of the parsed row destructured.
And we return the object that we want to return for each entry.
Conclusion
We can parse and create CSVs and TSVs with D3 and use them in our React app.