D3.js Axes, Ticks, and Gridlines
Definitions and implementation of customize axes, ticks, and gridlines to a D3.js chart, including information on tick methods.
Join the DZone community and get the full member experience.
Join For FreeThis article explains how to use scale, axis, and ticks methods to implement axes, ticks, and gridlines on D3.js charts. I will introduce some of the many D3.js methods that will allow you to customize your chart axes.
It is important to remember that the type of scale we use affect what axis methods we can use. D3.js provides many different types of scales. Some of these axis methods that we will discuss only apply to certain scales. In this case, we will focus on a bar chart, that has scaleBand on the horizontal direction, and scaleLinear on the vertical direction. This should cover most use cases.
I will use the CSV file that has some of the COVID-19 data. You can save the CSV file, and run the following command to emulate an API that serves the CSV file:
npx http-server --cors
This will start a http server that will serve the csv file that contains the data that we visualize using D3.js. The d3 chart will make request to this server and receives the csv file in response. In a real application, you will make a similar request to an API and receive the data back, usually in JSON format.
I will start off with a html template that has a simple d3 bar chart in it, and will add the axes and ticks to it.
xxxxxxxxxx
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://d3js.org/d3.v5.js"></script>
</head>
<body>
<h1>D3 Simple Bar Chart</h1>
<div id="chart-container"></div>
</body>
<script>
async function draw () {
const width = 800
const height = 500
const marginTop = 30
const marginRight = 30
const marginBottom = 30
const marginLeft = 50
const numOfCountries = 10
const title = "COVID-19 Death Count"
const svg = d3.select('#chart-container')
.append('svg')
.attr('width', width)
.attr('height', height)
.style('background-color', '#D3D3D3')
svg.append('text')
.attr('x', (marginLeft + width + marginRight) / 2)
.attr('y', marginTop / 2)
.attr('dy', '0.33em')
.text(title)
.attr('text-anchor', 'middle')
const dawData = await d3.csv('http://127.0.0.1:8080/covid-data.csv')
const data = dawData.filter(d => d.date === "2020-04-11" && d.location !== "World").sort((a, b) => b.new_deaths - a.new_deaths).filter((d, i) => i < numOfCountries).map(d => ({date: d.date, location: d.location, new_deaths: +d.new_deaths}))
const xScale = d3.scaleBand()
.domain(data.map(d => d.location))
.range([marginLeft, width - marginRight])
.padding(0.3)
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.new_deaths)])
.range([height - marginBottom, marginTop])
svg
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', d => xScale(d.location))
.attr('y', d => yScale(d.new_deaths))
.attr('width', xScale.bandwidth())
.attr('height', d => height - marginBottom - yScale(d.new_deaths))
.attr('fill', 'yellow')
}
draw()
</script>
</html>
Let us first focus on the X-axis. For the horizontal axis, we used a scale band:
xxxxxxxxxx
const xScale = d3.scaleBand()
.domain(data.map(d => d.location))
.range([marginLeft, width - marginRight])
.padding(0.3)
You start your axis by running one of the four axis methods (axisTop, axisRight, axisBottom, or axisLeft), and then set the scale by running the "scale" method, passing the scale you already defined to it.
axisTop, axisRight, axisBottom, and axisLeft, respectively add ticks to the top, right, bottom, and left of the axis.
Also, note that all of these axes are rendered at the origin. We can move them around using the transform attribute, as we will see in this example.
xxxxxxxxxx
const xAxis = d3.axisBottom()
.scale(xScale)
Now we create a group element and append our axis to it:
xxxxxxxxxx
svg.append('g')
.attr('transform', 'translate(0,' + (height - marginBottom) + ')')
.call(xAxis)
The X-axis should be visible on your chart now. Note that we transformed the axis to the bottom of the chart by using transform attribute, since all the axes are by default rendered at the origin.
Inspecting the axis we created, using your browser inspector, gives us good insight on how D3.js constructs the axis:
xxxxxxxxxx
<g transform="translate(0,470)" fill="none" font-size="10" font-family="sans-serif" text-anchor="middle">
<path class="domain" stroke="currentColor" d="M50.5,6V0.5H770.5V6"></path>
<g class="tick" opacity="1" transform="translate(95.43689320388344,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">United States</text>
</g>
<g class="tick" opacity="1" transform="translate(165.33980582524268,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">United Kingdom</text>
</g>
<g class="tick" opacity="1" transform="translate(235.2427184466019,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">France</text>
</g>
<g class="tick" opacity="1" transform="translate(305.1456310679611,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">Spain</text>
</g>
<g class="tick" opacity="1" transform="translate(375.04854368932035,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">Italy</text>
</g>
<g class="tick" opacity="1" transform="translate(444.9514563106796,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">Belgium</text>
</g>
<g class="tick" opacity="1" transform="translate(514.8543689320388,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">Germany</text>
</g>
<g class="tick" opacity="1" transform="translate(584.7572815533981,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">Iran</text>
</g>
<g class="tick" opacity="1" transform="translate(654.6601941747574,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">Brazil</text>
</g>
<g class="tick" opacity="1" transform="translate(724.5631067961167,0)">
<line stroke="currentColor" y2="6"></line>
<text fill="currentColor" y="9" dy="0.71em">Netherlands</text>
</g>
</g>
You can see that d3 creates the axis as a path with the class “domain”, and all the ticks are groups with the class “tick”. Knowing this allows you to select these elements and manipulate them with CSS and JavaScript.
Now that we have our basic axis up on the chart, let’s look at the different ways that we can customize it.
Tick Methods
Here is some D3.js vocabulary:
Inner ticks refer to the ticks that are associated with the data points (in this case, with each bar).
Outer ticks refer to the ticks that d3 adds to both ends of the axis.
Ticks refer to both inner ticks and outer ticks.
tickSize(size in px): Sets the size of the ticks (inner and outer) for the axis. It defaults to 6 px.
tickSizeInner (size in px): Sets the size of the inner ticks for the axis. It defaults to 6 px.
tickSizeOuter (size in px): Sets the size of the outer ticks for the axis. It defaults to 6 px.
tickPadding (size in px): Sets the size of the padding on each tick, which is the distance between the tick line and the tick text. It defaults to 3 px.
Here is an example of X axis that the outer tick size of 0, inner tick size of 3px, and the padding of 5px:
xxxxxxxxxx
const xAxis = d3.axisBottom()
.scale(xScale)
.tickSizeInner(3)
.tickSizeOuter(0)
.tickPadding(5)
If you would like to specify the values used for ticks explicitly, you can use tickValues method and pass an array of desired values to it:
xxxxxxxxxx
const xAxis = d3.axisBottom()
.scale(xScale)
.tickSizeInner(3)
.tickSizeOuter(0)
.tickPadding(5)
.tickValues(['Germany', "United States"])
Now the only ticks that appear on the X axis is for Germany and the United States.
Another useful method is Ticks. It usually takes this form:
ticks(count, [format])
This method sets the number of ticks to “count”, and applies “format” to tick values. Note that this methods does not apply to scaleBand and scalePoint, so let’s try it on our Y axis.
xxxxxxxxxx
const yAxis = d3.axisLeft()
.scale(yScale)
.ticks(20, "~s")
This axis will have 20 ticks, and format the tick values (“~s”
means using SI System prefixes, and trim the trailing insignificant zeros. Formatting requires an entire article in its own right).
tickArguments([arguments])
This method is another way to implement ticks method. The following is equivalent to the previous code snippet:
xxxxxxxxxx
const yAxis = d3.axisLeft()
.scale(yScale)
.tickArguments([20, '~s'])
tickFormat(format)
This method is another method to format your ticks. The following two snippets are equivalent:
xxxxxxxxxx
const yAxis = d3.axisLeft()
.scale(yScale)
.tickFormat(d3.format("~s"))
.ticks(20)
const yAxis = d3.axisLeft()
.scale(yScale)
.ticks(20, "~s")
You must have noticed that the ticks method is the most versatile method, which combines what tickFormat and tickArguments do.
Now you might want to add gridlines to you chart, in order to make it easier to read the height of each bar on a bar chart, line on a line chart, etc. We can use a trick to apply gridlines to our charts.
Let’s demonstrate adding gridlines to our y axis. To accomplish this, we will add another y-axis, call it yGrid, remove the axis line and the tick values, and extend the ticks in the opposite direction, across the width of the chart. We will also give a class name to our new y-axis (yGrid), and the old y-axis (yAxis), so that we can later use CSS to style them differently. We most likely want to fade the gridline so they blend better with the bars.
xxxxxxxxxx
const yGrid = d3.axisLeft()
.scale(yScale)
.tickFormat('')
.ticks(5)
.tickSizeInner(-width + marginLeft + marginRight)
svg.append('g')
.attr('class', 'y-grid')
.attr('transform', 'translate(' + marginLeft + ', 0)')
.call(yGrid)
Using these methods, you can make it much easier for the users of your charts to read the data.
Opinions expressed by DZone contributors are their own.
Comments