The functionality of the d3 Bar chart with a tool tip seems to be malfunctioning

Working on a D3 svg chart with built-in tooltips using the d3-tip library. Check out the original code here.

Utilizing Django as the back end to populate log count per year from datetime. Successfully populated axis and labels except for the bars.

Here is the html template named graph.html:

<!DOCTYPE html>
<meta charset="utf-8">
... (Code continued)
</script>
</body>
</html>

In views.py, the following code successfully finds the count by year:

def graph(request):
    return render(request, 'graph/graph.html')

def log_count_by_year(request):
    data = log_runs.objects.all() \
        ... (Code continued)
    return JsonResponse(list(data), safe=False)

Successfully receiving JSON object through API call, here is the expected JSON object:

[{"count_items": 22, "year": "2017-01-01T00:00:00Z"}, ... (JSON data continued)]

Encountering an issue where only axes and labels are visible in the front end, but no bar graphs displayed. Any assistance on identifying the problem would be greatly appreciated!

Answer №1

Your dilemma lies in the fact that a time scale does not support rangeBand().

Considering that you have years as a categorical variable and not a quantitative one (since this is a bar chart, not a line chart), my suggestion is to switch your scale to an ordinal one:

var x = d3.scale.ordinal()
    .rangeBands([0, width], 0.2);

Next, remove your parser and update your domain accordingly:

x.domain(data.map(function(d) {
    return d.year;
}));

Lastly, ensure to invoke the tooltip:

svg.call(tip);

Here's your revised code with these modifications:

<style>
  body {
    font: 10px sans-serif;
  }
  
  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
  
  .bar {
    fill: orange;
  }
  
  .bar:hover {
    fill: orangered;
  }
  
  .x.axis path {
    display: none;
  }
  
  .d3-tip {
    line-height: 1;
    font-weight: bold;
    padding: 12px;
    background: rgba(0, 0, 0, 0.8);
    color: #fff;
    border-radius: 2px;
  }
  /* Creates a small triangle extender for the tooltip */
  
  .d3-tip:after {
    box-sizing: border-box;
    display: inline;
    font-size: 10px;
    width: 100%;
    line-height: 1;
    color: rgba(0, 0, 0, 0.8);
    content: "\25BC";
    position: absolute;
    text-align: center;
  }
  /* Style northward tooltips differently */
  
  .d3-tip.n:after {
    margin: -1px 0 0 0;
    top: 100%;
    left: 0;
  }

</style>

<body>
  <script src="https://d3js.org/d3.v3.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>

  <script>
    var margin = {
        top: 40,
        right: 20,
        bottom: 30,
        left: 40
      },
      width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

    var x = d3.scale.ordinal()
      .rangeBands([0, width], 0.2);

    var y = d3.scale.linear()
      .range([height, 0]);

    var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left");

    var tip = d3.tip()
      .attr('class', 'd3-tip')
      .offset([-10, 0])
      .html(function(d) {
        return "<strong>Log Count:</strong> <span style='color:red'>" + d.count_items + "</span>";
      })


    var 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 + ")");
      
      svg.call(tip);

    var data = [{
      "count_items": 22,
      "year": "2017-01-01T00:00:00Z"
    }, {
      "count_items": 16,
      "year": "2016-01-01T00:00:00Z"
    }, {
      "count_items": 16,
      "year": "2015-01-01T00:00:00Z"
    }, {
      "count_items": 6,
      "year": "2014-01-01T00:00:00Z"
    }, {
      "count_items": 1,
      "year": "2013-01-01T00:00:00Z"
    }, {
      "count_items": 1,
      "year": "2012-01-01T00:00:00Z"
    }, {
      "count_items": 2,
      "year": "2011-01-01T00:00:00Z"
    }, {
      "count_items": 1,
      "year": "2010-01-01T00:00:00Z"
    }, {
      "count_items": 2,
      "year": "2009-01-01T00:00:00Z"
    }, {
      "count_items": 1,
      "year": "2008-01-01T00:00:00Z"
    }, {
      "count_items": 1,
      "year": "2007-01-01T00:00:00Z"
    }, {
      "count_items": 2,
      "year": "2006-01-01T00:00:00Z"
    }, {
      "count_items": 1,
      "year": "2005-01-01T00:00:00Z"
    }, {
      "count_items": 1,
      "year": "2004-01-01T00:00:00Z"
    }];

    data.forEach(function(d) {
      d.year = d.year.split("-")[0];
      d.count_items = +d.count_items;
    });

    x.domain(data.map(function(d) {
      return d.year;
    }));

    y.domain([0, d3.max(data, function(d) {
      return d.count_items;
    })]);

    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", -38)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Log count");

    svg.selectAll(".bar")
      .data(data)
      .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) {
        return x(d.year);
      })
      .attr("width", x.rangeBand())
      .attr("y", function(d) {
        return y(d.count_items);
      })
      .attr("height", function(d) {
        return height - y(d.count_items);
      })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide)

  </script>

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

How can the datetime value of the Apex Charts datapoint be shown in the tooltip?

I'm struggling to find the proper location within the w.globals object to display the x-axis value, which is a datetime, in the tooltip of the datapoint. var chartOptions = { ... xaxis: { type: "datetime" }, tooltip: { x: { format: " ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

Tips for improving performance with ng-repeat directive?

I have encountered some performance issues while using socket.io with the ng-repeat directive in Angular. The application slows down significantly when receiving a large amount of data from the backend, making it impossible to interact with the app. What w ...

The error message encountered in Python is: "Cannot iterate over the '_csv.writer' object due to a TypeError."

I'm currently facing an error while parsing json to csv: for i in data: TypeError: '_csv.writer' object is not iterable Here is the code snippet: import json import csv with open("Data.json", 'r') as file: data = json.load( ...

Extract the HTML table from Gmail and transfer it to Google Sheets with the help of Google Apps Script

Just dipping my toes into google apps script. On my to-do list is creating a script that can extract data from a table in Gmail and transfer it to Google Sheets. Here's an example of what the email body looks like: CONFIRMATION CODE GUEST&apo ...

Using nested ternary operations in React can cause issues with accessing local variables

Note: I encountered an issue where the extra curly braces around the first ternary result did not solve my initial problem. I replaced them with parentheses. Josep's suggestion to use getTime required me to equate the dates. The Date().setHours(0, 0, ...

python decoding json using Twisted

Here's the code I've written using the Python Twisted library: class Cache(protocol.Protocol): def __init__(self, factory): self.factory = factory def dataReceived(self, data): request = json.loads(data) self.fac ...

Reasons why the Express Route fails to store cache while executed in a separate file

My code works fine when it's all in one file, but the caching stops working when I move it to a separate middleware file. Can someone help me understand why the caching isn't functioning properly in my middleware? Here is the working code: var e ...

What is the correct way to submit a form object on a website?

Currently, I am practicing CBV and wanted to test if I can override methods. One major issue I encountered is that I am unsure how to utilize recently submitted data. In an attempt to address this, I have crafted the following code for a DetailView, which ...

Troubleshooting: Jquery UI Draggable - Cursor losing track of draggable element

I want to create a draggable popup with Jquery UI functionality, but I'm facing an issue where the cursor does not stay aligned with the popup element when dragged. When dragging the popup element to the left, the mouse cursor goes beyond the div elem ...

Element sticking on scroll down and sticking on scroll up movements

I am currently working on a sticky sidebar that catches and stays fixed at a certain scroll point using JavaScript. However, I am facing an issue where I need the sidebar to catch when scrolling back up and not go further than its initial starting point. ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

Issues with jQuery ajax when trying to access remote JSON data

Even though I receive a json response when entering the URL in my browser, I am unable to access it using my code. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $.ajax({ url:"http ...

Can Comet be implemented without utilizing PrototypeJs?

Can Comet be implemented without utilizing PrototypeJs? ...

Harnessing the Power of Script Loader in Your webpack.config.json File

I'm taking my first steps into the webpack world with Vue.js and vueify for ES6 modules. I've run into a challenge when it comes to loading third-party jQuery plugins. I've successfully used the ProvidePlugin to load jQuery. plugins: [ ...

The fs.fsync(fd, callback) function in the node.js API allows you

Can you explain the purpose of fs.fsync(fd, callback) in the Node.js API? fs.fsync(fd, callback) This function is used for asynchronous fsync(2). The completion callback only returns an exception if there is one. fs.fsyncSync(fd) This function is for ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

How can I use querySelector in JavaScript to target all div elements that have the same class?

I'm having an issue with the document.querySelector in my JavaScript code. It currently only selects the first div that contains the class "test", but I need it to select all such divs. Is there a way to achieve this using my existing JavaScript? ...

I'm having trouble getting my home.js to render in the outlet component

After using Material-UI to create navbar.js, I encountered an issue where the other component was not rendering in the <Outlet/> Component RootLayout.js import { Outlet } from "react-router-dom"; import NavBar from "../component/NavBa ...

Fetch and showcase JSON information from a CodeIgniter method

Is there a way to retrieve data from a SQL database using ajax (json) with Codeigniter or PHP? I have attempted it, but the result shows up as "undefined." Here is the code snippet: My jQuery code snippet: $('[id^="menuitem_"]').on('click& ...