1 year ago

#325829

test-img

ignacioct

XHTML file build from HTML is not showing D3.js graph, even though HTML did show it

I'm trying to create an XHTML file with a D3 graph, from a previous HTML file. My HTML looks like this:

<!DOCTYPE html>
<html>
  <head>
    <style>
      .bar {
        fill: red;
      }
    </style>
    <script src="d3.v4.js"></script>
  </head>
  <body>
    <svg width="500" height="400"></svg>
    <script src="bar_chart.js"></script>
  </body>
</html>

This shows this:

enter image description here

However, when I turn this into XHTML:

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <style>
      .bar {
        fill: red;
      }
    </style>
    <script src="../script/d3.v4.js"></script>
  </head>
  <body>
    <svg width="500" height="400"></svg>
    <script src="../script/bar_chart.js"></script>
  </body>
</html>

It shows this:

enter image description here

This is the JS script that's generating the bar chart.

var dataset1 = [33, 57, 84, 21, 60];

var svg = d3.select("svg"),
  margin = 200,
  width = svg.attr("width") - margin,
  height = svg.attr("height") - margin;

var xScale = d3.scaleBand().range([0, width]).padding(0.5),
  yScale = d3.scaleLinear().range([height, 0]);

var g = svg.append("g").attr("transform", "translate(" + 100 + "," + 100 + ")");

xScale.domain(dataset1);
yScale.domain([0, 100]);

g.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(
    d3.axisBottom(xScale).tickFormat(function (d) {
      return "sale: " + d;
    })
  );

g.append("g").call(
  d3
    .axisLeft(yScale)
    .tickFormat(function (d) {
      return "$" + d;
    })
    .ticks(4)
);

g.selectAll(".bar")
  .data(dataset1)
  .enter()
  .append("rect")
  .attr("class", "bar")
  .attr("x", function (d) {
    return xScale(d);
  })
  .attr("y", function (d) {
    return yScale(d);
  })
  .attr("width", xScale.bandwidth())
  .attr("height", function (d) {
    return height - yScale(d);
  });

Do you guys what I'm missing? I supposed that turning HTML into XHTML was just following some more guidelines and specifying at the top that it's an XHTML. Is D3 incompatible?

Thank you for your support.

javascript

html

d3.js

xhtml

0 Answers

Your Answer

Accepted video resources