Tips for organizing a date with d3's time.format

This JSFiddle and the snippet provided below demonstrate the usage of the format "%d-%b-%y" for dates. The code example showcases how to work with dates in this format, such as "1-May-12".

"%d-%b-%y"

Here is a sample code snippet:

var margin = {
    top: 30,
    right: 20,
    bottom: 30,
    left: 50
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;

var parseDate = d3.time.format("%d-%b-%y").parse;

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

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

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

var valueline = d3.svg.line()
    .x(function (d) {
      return x(d.date);
    })
    .y(function (d) {
      return y(d.close);
    });

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 + ")");

// Get the data
var data = [{
    date: "1-May-12",
    close: "58.13"
}, {
    date: "30-Apr-12",
    close: "53.98"
}, {
    date: "27-Apr-12",
    close: "67.00"
}, {
    date: "26-Apr-12",
    close: "89.70"
}, {
    date: "25-Apr-12",
    close: "99.00"
}];

data.forEach(function (d) {
    d.date = parseDate(d.date);
    d.close = +d.close;
});

// Scale the range of the data
x.domain(d3.extent(data, function (d) {
    return d.date;
    }));
y.domain([0, d3.max(data, function (d) {
    return d.close;
    })]);

svg.append("path") // Add the valueline path.
.attr("d", valueline(data));

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

svg.append("g") // Add the Y Axis
.attr("class", "y axis")
    .call(yAxis);
body {
    font: 12px Arial;
}
path {
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
}
.axis path, .axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Answer №1

Are you satisfied with this solution?

var margin = {
    top: 30,
    right: 20,
    bottom: 30,
    left: 50
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;

var parseDate = d3.time.format("%d-%m-%y").parse;

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

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

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

var valueline = d3.svg.line()
    .x(function (d) {
      return x(d.date);
    })
    .y(function (d) {
      return y(d.close);
    });

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 + ")");

// Retrieve the data
var data = [{
    date: "1-1-12",
    close: "58.13"
}, {
    date: "30-2-12",
    close: "53.98"
}, {
    date: "27-3-12",
    close: "67.00"
}, {
    date: "26-4-12",
    close: "89.70"
}, {
    date: "25-5-12",
    close: "99.00"
}];

data.forEach(function (d) {
    d.date = parseDate(d.date);
    d.close = +d.close;
});

// Adjust the range of the data
x.domain(d3.extent(data, function (d) {
    return d.date;
    }));
y.domain([0, d3.max(data, function (d) {
    return d.close;
    })]);

svg.append("path") // Include the valueline path.
.attr("d", valueline(data));

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

svg.append("g") // Implement the Y Axis
.attr("class", "y axis")
    .call(yAxis);
body {
    font: 12px Arial;
}
path {
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
}
.axis path, .axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<body></body>

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

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

Getting into particular fields of an embedded object array using a dynamic variable in Meteor: a step-by-step guide

Users have defined an array of strings with different combinations: pickedStrings = ["A", "B", "G", "L", "Y"]; This can also be: pickedStrings = ["A", "G"] or pickedStrings = ["A", "L", "Y"] or any other mix. More strings may be added in the future. ...

An unexpected error occurred in React.js when trying to use WebRTC RTCPeerConnection.addStream function, indicating

I'm trying to create a basic video chat using react.js and WebRTC. However, I'm encountering an error on line pc.addStream(localStream): TypeError: Argument 1 of RTCPeerConnection.addStream is not an object. Additionally, I can't seem to ...

Can JavaScript be utilized to dynamically adjust the size of all elements on the screen to a specified percentage of their initial height and width when a certain event occurs?

I'm fairly new to the world of JavaScript, but I have a basic understanding of it. I want to optimize my personal website for mobile devices. I've already taken care of screen orientation and element positioning, everything is centered nicely and ...

I am looking to implement screen reader capabilities for both the select-2 combo box and bootstrap's datetime-picker. How can I go about doing

On my existing website, I have select-2 combo boxes for drop-down lists and a Bootstrap Calendar widget. While these features work well, they lack accessibility for users with disabilities. In an effort to make the website inclusive for everyone, I am work ...

HighStock chart malfunctioning with inaccurate epoch datetime display

I am working on a project that involves creating a dynamic Highstock chart to showcase the daily influx of emails. The data is stored in a JSON file that gets updated every day, and you can see a snippet of it below: [{ "name": "Month", "data": [147199320 ...

Managing and Streaming Music in a Rails Application

Currently, I am storing mp3s using paperclip and they only play back if I utilize Amazon S3. However, I am hesitant to use Amazon S3 because I am unsure how to secure the files. Now, I am reconsidering my approach as I need to secure the mp3s and provide ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

I am having trouble getting the unix timestamp to work with Meteor's API, pickadate.js

Based on the information from the API at , I have implemented the following code to retrieve a Unix timestamp based on a selected date. Initially, I configured: $('.startDate').pickadate({ selectMonths: true, selectYears: 15 ...

Guide to making a basic cross-domain ajax request that fetches an HTML webpage

I have been researching various methods for making cross domain calls using ajax, but they all seem overly complex or too specific. Below is a basic HTML page where I am trying to send request parameters to a specific JSP on my server. <!DOCTYPE html&g ...

JavaFX: We are experiencing issues with our JavaScript file when we compile the HTML and add the link to the header. What could be causing this problem?

There is a need for the user to be able to change the value, and as a result, the numbers should automatically update. I am facing this issue where the values are not changing correctly. Additionally, I was wondering if it is feasible to link a JS file in ...

Modify the text inside a div based on the navigation of another div

Hey there, experts! I must confess that I am an absolute beginner when it comes to JavaScript, JQuery, AJAX, and all the technical jargon. Despite my best efforts, I'm struggling to grasp the information I've found so far. What I really need is ...

Unspecified behavior for a dropdown menu within an Angular form

I'm a newcomer to Angular and currently struggling with displaying the selected values of form elements in the console. Surprisingly, all other elements get printed except for the select list element which shows up as undefined. Here's an overvie ...

The JQuery autocomplete feature is providing a data array with labels and values, however, it is not displaying the labels as suggestions

Currently, I am implementing an AJAX call using Jquery-autocomplete on a WordPress website. The call returns a list of airports with their corresponding Airport ID as the value. However, I am encountering an issue where the input is not displaying anythin ...

Choosing a lone column in amcharts 4

Is there a way to highlight just one column and unhighlight any previously highlighted columns in an amCharts 4 Column chart? I've been attempting to adjust the colors of all the columns before highlighting the target column, but it doesn't seem ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

Discovering an element within an HTML response using jQuery AJAX

Check out the code snippet below: ajax_obj = $.ajax( { data: data, success: function(answer) { console.log(answer); console.log($('#table_conferences_tbody', answer).html()); ...

Use multiple lines to create a stunning visualization using morris.js. Let your data

I need help creating a graph using morris.js with 2 lines. I have two sets of data in one array, but I can't seem to display both lines on the graph simultaneously. When I use todos[0], only the first line is visible, and when I use todos[1], only the ...

Is there a universal framework for PHP and JavaScript commands?

Looking for frameworks that handle PHP <=> JS (AKA "AJAX") communication with all the necessary boilerplate code included to make development smoother. Are there any options worth considering? I know there are libraries out there, but most I've ...

How come my strategies for React function components aren't producing results?

Currently, I am working on a project that involves utilizing the Moviedb API. In this project, I have developed a Movie component to display a list of movies and handle API requests. From the Movie component, I pass on the movie's release date and gen ...