Το D3.js είναι μια βιβλιοθήκη JavaScript για το χειρισμό δεδομένων HTML. <p>Το D3.js είναι εύκολο στη χρήση.
Για να χρησιμοποιήσετε το D3.js στην ιστοσελίδα σας, προσθέστε έναν σύνδεσμο στη βιβλιοθήκη:
<script src="https://d3js.org/d3.v4.js"></script>
Αυτό το σενάριο επιλέγει το στοιχείο του σώματος και προσθέτει μια παράγραφο με το κείμενο "Hello World!":
d3.select("body").append("p").text("Hello World!");
Δοκιμάστε το μόνοι σας →
<!DOCTYPE html>
<html>
<script src="//d3js.org/d3.v4.js"></script>
<body>
<h2>D3.js is Easy to Use</h2>
<p>The script below selects the body element and appends a paragraph with the text "Hello World!":</p>
<script>
d3.select("body").append("p").text("Hello World!");
</script>
</body>
</html>
// Set Dimensions
const xSize = 500;
const ySize = 500;
const margin = 40;
const xMax = xSize - margin*2;
const yMax = ySize - margin*2;
// Create Random Points
const numPoints = 100;
const data = [];
for (let i = 0; i < numPoints; i++) {
data.push([Math.random() * xMax, Math.random() * yMax]);
}
// Append SVG Object to the Page
const svg = d3.select("#myPlot")
.append("svg")
.append("g")
.attr("transform","translate(" + margin + "," + margin + ")");
// X Axis
const x = d3.scaleLinear()
.domain([0, 500])
.range([0, xMax]);
svg.append("g")
.attr("transform", "translate(0," + yMax + ")")
.call(d3.axisBottom(x));
// Y Axis
const y = d3.scaleLinear()
.domain([0, 500])
.range([ yMax, 0]);
svg.append("g")
.call(d3.axisLeft(y));
// Dots
svg.append('g')
.selectAll("dot")
.data(data).enter()
.append("circle")
.attr("cx", function (d) { return d[0] } )
.attr("cy", function (d) { return d[1] } )
.attr("r", 3)
.style("fill", "Red");
Δοκιμάστε το μόνοι σας →
<!DOCTYPE html>
<html>
<script src="https://d3js.org/d3.v4.js"></script>
<body>
<h2>D3.js Scatter-Plot</h2>
<svg id="myPlot" style="width:500px;height:500px"></svg>
<script>
// Set Dimensions
const xSize = 500;
const ySize = 500;
const margin = 40;
const xMax = xSize - margin*2;
const yMax = ySize - margin*2;
// Create Random Points
const numPoints = 100;
const data = [];
for (let i = 0; i < numPoints; i++) {
data.push([Math.random() * xMax, Math.random() * yMax]);
}
// Append SVG Object to the Page
const svg = d3.select("#myPlot")
.append("svg")
.append("g")
.attr("transform","translate(" + margin + "," + margin + ")");
// X Axis
const x = d3.scaleLinear()
.domain([0, 500])
.range([0, xMax]);
svg.append("g")
.attr("transform", "translate(0," + yMax + ")")
.call(d3.axisBottom(x));
// Y Axis
const y = d3.scaleLinear()
.domain([0, 500])
.range([ yMax, 0]);
svg.append("g")
.call(d3.axisLeft(y));
// Dots
svg.append('g')
.selectAll("dot")
.data(data).enter()
.append("circle")
.attr("cx", function (d) { return d[0] } )
.attr("cy", function (d) { return d[1] } )
.attr("r", 3)
.style("fill", "Red");
</script>
</body>
</html>