75267

d3.js, how can i create an axis with custom labels and customs ticks?

Question:

I have an array similar to this:

[{year: 1999, val: 5}, {year: 2002, val: 8}]

and I would like to add an axis where I have one tick for each year value (something I can do with tickValues and tickFormat) but where the tick label is not only the year but has a custom format, so the result could be something like "1999: 5" for the first array element.

To rephrase it:

Where I'm now

const xAxis = d3.axisTop(xScale) .tickValues(data.map(d => d.year);

This is not ok because only the year is visualized on the label of the tick and I would like to use a custom format.

Is this possible with d3?

Answer1:

You could try like this

const xAxis = d3.axisTop(xScale) .tickValues(data) .tickFormat(d => (d.year +":"+ d.val));

Answer2:

Since you didn't show the scale in your question we don't know what type of scale you have and what are the domain values. But one thing is sure: you cannot pass the whole object to it. Therefore, your tickFormat doesn't have access to one of the properties in each object.

A simple solution is using the index of the tick to get the other property, provided that you are displaying <strong>all</strong> the ticks (and that you are using an ordinal scale):

var axis = d3.axisBottom(scale) .tickFormat(function(d, i) { return d + ": " + data[i].val; });

Here is a demo:

<pre class="snippet-code-js lang-js prettyprint-override">var svg = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 100); var data = [{ year: 1999, val: 5 }, { year: 2002, val: 8 }, { year: 2005, val: 1 }, { year: 2008, val: 4 }, { year: 2011, val: 9 }, { year: 2014, val: 2 }]; var scale = d3.scalePoint() .range([20, 480]) .domain(data.map(function(d) { return d.year })); var axis = d3.axisBottom(scale) .tickFormat(function(d, i) { return d + ": " + data[i].val; }); var gX = svg.append("g") .attr("transform", "translate(0,50)") .call(axis); <pre class="snippet-code-html lang-html prettyprint-override"><script src="https://d3js.org/d3.v4.min.js"></script>

Answer3:

What I have been able to do now:

d3.axisTop(xScale) .tickValues(data.map(d => d.year)) .tickFormat((d, i) => data[i].val);

Quite ugly but it works. If I get a better solution I will accept a different one.

Recommend

  • D3 only one Y-axis on right for plotting line chart
  • Writing to TcpClient and NetworkStream
  • Android Billing how to use setAccountId or assign payment to custom identifier
  • How to change the size of dots in beeswarm plots in D3.js
  • Cannot read property “0” of undefined
  • Log scale (x axis) histogram
  • visualizing RDF query result
  • Adding foreignObjects to D3 force-directed graph nodes breaks events
  • there is no graph with tensorboard
  • WPF version of .ScaleControl?
  • blade.php method outputting it's result to the form
  • Android app gives error “BatteryStatsImpl: reading network stats”
  • How to get current document uri in XSLT?
  • Intel-64 and ia32 atomic operations acquire-release semantics and GCC 5+
  • Silverlight DependencyProperty.SetCurrentValue Equivalent
  • D3 get axis values on zoom event
  • How to use JavaScript to determine whether a file exists in a directory?
  • How do I access an unhandled exception in an MVC Error view?
  • Replace value with Factor in r data.table
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Javascript Callbacks with Object constructor
  • Sending data from AppleScript to FileMaker records
  • Fill an image in a square container while keeping aspect ratio
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Weird JavaScript statement, what does it mean?
  • Apache 2.4 - remove | delete | uninstall
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • KeystoneJS: Relationships in Admin UI not updating
  • AngularJs get employee from factory
  • Benchmarking RAM performance - UWP and C#
  • Load html files in TinyMce
  • Running Map reduces the dimensions of the matrices
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • Unable to use reactive element in my shiny app
  • Android Heatmap on canvas or ImageView
  • Conditional In-Line CSS for IE and Others?