I'd like to create a chart with d3.js. Could someone tell me how to work with the jsondata[timestamp,price]. I get the data from coingeckoAPI and it looks like that:
{"prices":[[1649667011317,38721.07051511258],[1649667168163,38726.36780848938],[1649667622285,38750.30201896313],[1649667926510,38715.36968177588],[1649668246571,38705.597785934006],[1649668432287,38690.34512542588],[1649668897715,38620.57305041674],[1649669050953,38613.10740572825],[1649669284813,38568.32503183882],[1649669697192,38518.76279413846],[1649669982557,38491.21941297744],[1649670258121,38460.7219359208],[1649670606639,38417.38270710583],[1649670978757,38349.85248699985],[1649671244134,38336.437837571124],
thats my Php Code:
function history($url) {
$ch= curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$resp = curl_exec($ch);
if ($e= curl_error($ch)) {
echo $e;
}
else {
return $resp;
}
curl_close($ch);
}
and HTML:
<?php echo history("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=eur&days=1");
?>
My Answer:
To create a chart with d3.js using the data from the coingeckoAPI, you can follow these steps:
1. Parse the JSON data received from the API:
javascript
let data = JSON.parse(jsondata);
2. Extract the timestamp and price values from the data:
javascript
let prices = data.prices.map(d => [d[0], d[1]]);
3. Create a line chart using d3.js:
javascript
// Set the dimensions and margins of the graph
let margin = {top: 20, right: 20, bottom: 30, left: 50};
let width = 600 - margin.left - margin.right;
let height = 400 - margin.top - margin.bottom;
// Append the svg object to the body of the page
let svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// X scale and axis
let x = d3.scaleTime()
.domain(d3.extent(prices, d => new Date(d[0])))
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Y scale and axis
let y = d3.scaleLinear()
.domain([0, d3.max(prices, d => d[1])])
.range([height, 0]);
svg.append("g")
.call(d3.axisLeft(y));
// Line function
let line = d3.line()
.x(d => x(new Date(d[0])))
.y(d => y(d[1]));
// Add the line
svg.append("path")
.datum(prices)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", line);
4. Make sure to include the d3.js library in your HTML file:
html
5. Display the chart on your webpage by running the PHP code and rendering the SVG element:
html
Rate this post
5 of 5 based on 8859 votesComments