Ordering in D3 Code

I'm struggling with understanding the correct structure for writing D3 code.

For example: In the code snippet below, I noticed that if I place the 3rd section (Chart Title) of the code after creating the svg element, the title text doesn't display. However, if I mention the 3rd section before creating the svg, the chart works as expected.

Why is that?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

<style>

    circle.dimple-series-1{
    fill: red;
    }    

    h2{
    color: black;
    text-align: center;
    font-family: monospace;
    font-size: 20px;
    }   

    </style>

  <script src="http://d3js.org/d3.v3.min.js"></script>
  <script src="http://dimplejs.org/dist/dimple.v2.0.0.min.js"></script>
    <script type="text/javascript">
      function draw(data) {

      /*
        Setting up D3.js
      */

          "use strict";
          var margin = 75,
              width = 1400 - margin,
              height = 600 - margin;

          /*Adding TITLE*/

          d3.select("body")
          .append("h2").text("Goals by Year!");

          /*Creating SVG Element*/

          var svg = d3.select("body")
            .append("svg")
              .attr("width", width + margin)
              .attr("height", height + margin)
            .append('g')
            .attr('class','chart');

      /*
        Constructing Dimple.js Chart
      */

          var myChart = new dimple.chart(svg, data);
          var x = myChart.addTimeAxis("x", "year"); 
          x.dateParseFormat="%Y"
          x.tickFormat="%Y";
          x.timeInterval= 4;
          myChart.addMeasureAxis("y", "attendance");
          myChart.addSeries(null, dimple.plot.line);
          myChart.addSeries(null, dimple.plot.scatter);


          myChart.draw();
        };
      </script>
  </head>
<body>
  <script type="text/javascript">
  /*
    Using D3 to load the TSV file
    and passing the data to the draw function
    */
  d3.tsv("world_cup.tsv", draw);
  </script>
</body>
</html>

Answer №1

The title is not being added to the SVG, but instead, a heading object is being appended to the body. It's possible that the title isn't showing up because it's being added after the SVG in the DOM and may be out of view depending on your CSS settings. However, the element should still be present.

In one scenario, your DOM structure will appear as follows:

<body>
    <h2>Goals by Year!</h2>
    <svg>
       <... Dimple Stuff ...>
    </svg>
</body>

And in another scenario, it will look like this:

<body>
    <svg>
       <... Dimple Stuff ...>
    </svg>
    <h2>Goals by Year!</h2>
</body>

If you wish to incorporate the title directly into the SVG using SVG shapes, you'll need to target the SVG element instead of the body like so:

var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin)
        .attr("height", height + margin);

svg.append("text")
    .attr("x", 100)
    .attr("y", 100)
    .style("fill", "black")
    .text("Goals by Year!");

... Dimple Stuff

With this method, your DOM will resemble the following structure:

<body>
    <svg>
       <text x=100 y=100 style="fill:black">Goals by Year!</text>
       <... Dimple Stuff ...>
    </svg>
</body>

Edit: Note removed. Dimple appears to work well with using a group inside the SVG.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating a background image into a card component using props

I attempted to add a background image to the card component through props, but the image failed to display on the card. I didn't encounter any errors, and I'm unsure what mistake I might be making. Any suggestions or alternative solutions would b ...

Using AngularJS to implement validation on radio buttons

My application is a cross-platform app that utilizes AngularJS, Monaca, and Onsen UI. Within one of the views, there exists an array of list items where each item can be associated with a random number of radio buttons. These lists are dynamically generat ...

Transfer data in scripts to dynamically load Ajax pages

Is there a way to send variables or parameters from the original page to a script tag on another page that is loaded using jQuery Ajax? Here are the scripts: Page 1 <script> $(function(){ $('#button').click(function(){ $.ajax({ type:"P ...

Why was the 'Symbol' type introduced in ECMA-262-v6 and what purpose does it serve?

Can you explain the purpose of the 'Symbol' type in ECMA-262-v6? Is it used for fast path implementation for object keys? How does it work internally - does it hash with the assurance that the underlying data remains unchanged? ...

When do Angular.js memory leaks become a cause for concern?

My application is quite large, built on angular with nested states, directives, and data tables. We recently decided to switch to a full single-page setup, which raised some performance concerns. While Chrome seems unaffected visually, Firefox appears to s ...

Retrieve the unfinished user input from React's Material UI Autocomplete

I've implemented Material UI's Autocomplete input with react-hook-form as shown below: import React from "react"; import {Controller} from "react-hook-form"; import {Autocomplete} from "@mui/material"; export const ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

Incorporate tinyMCE into a colorbox module

Currently, I am facing an issue on my website where there are textareas with tinymce. While I can view all the textareas correctly, when trying to open colorbox within a textarea, it does not inherit the tinymce properties. The code snippet used to open co ...

Utilizing Next.js to conditionally display data

My current challenge involves rendering data fetched from an API. The data is in JSON format, and I have a conditional logic to push a specific element based on the fetch result. {status: 'success'} If the fetch fails, I need to handle it by pus ...

What is the best way to incorporate markers into my d3 line chart that includes two separate datasets?

In my JavaScript code, I'm creating a line chart for two datasets using the d3 library with Vue framework integration. Within the HTML code, there are buttons that trigger the updateData function to display the line charts for the respective datasets ...

Encountering a node.js issue

Hi there, I keep encountering this error message. Can someone explain what it means? I'm not very skilled in coding, so I would appreciate any assistance :) Best regards logon fail: 65, sessionID: 6343803 events.js:85 throw er; // Unhandled & ...

What is the best way to conceal a website's URL?

Is it possible to hide the actual URL some.otherdomain.com and show only domain.com to visitors of my website? I am looking for a way to mask the URL, perhaps through .htaccess or javascript. Is there any solution available? ...

Using dynamic values in Angular functions

Here is the code snippet I am working with: $scope.testByValue = function() { $scope.fChanged($scope.lists.title); }; But I am facing an issue on the page where the value for: $scope.testValue = testValue; The variable testValue is being assigned a ...

Switch the image displayed on hover over an image using the #map attribute

Recently, I successfully integrated a database connection into this website and made it dynamic. The overall design of the site was already in place, so my main focus was on adding the functionality of the database connection. However, after implementing ...

Is there a way to programmatically display an edit text field on an HTML page?

Currently, I have a straightforward task which involves pulling data from a MySQL database to display in an HTML table. Here is the current script: <html> <body> <table border='1'> <?php mysql_connect('url',&ap ...

Retrieving Angular URL Parameters Containing Slashes

I'm currently in the process of developing a single page angular application. This app retrieves a token from the URL and then sends it to an API. At the moment, my URL structure is as follows: www.example.com/?token=3d2b9bc55a85b641ce867edaac8a9791 ...

Ways to retrieve HTML content from various spans and incorporate the values as classes

Here is my custom HTML: <div class="box"> <ul class="fourcol first"> <li class="feature-item">Description: <span>0</span></li> <li class="feature-item">Description: <span>0</span></ ...

Tips for adjusting the width of a Facebook embedded video within its container using ReactPlayer

Has anyone encountered issues with adding an embedded video to a NextJS app using ReactPlayer and Facebook videos? It seems that Facebook does not support the width="100%" attribute, as it always snaps back to 500px. Interestingly, this works wel ...

filtering the properties of mongoose documents

I have created a schema as shown below: var UserSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true }, location: { type: String, required: true }, p ...

Automate the process of filling up and activating a bootstrap dropdown upon a click, and clearing it out when it is

Is there a method to reveal the dropdown content only upon clicking instead of displaying all content at once and increasing the lines of HTML code? Perhaps using an onclick attribute on the button and incorporating a function inside? var data = [{ " ...