Let’s take:
X | Y |
---|---|
0 | 10 |
1 | 15 |
2 | 35 |
3 | 20 |
And make:
D3.js is mindbending, and I find the examples on the D3.js wiki to be too little explanation with too much going on. In this example, I will show you how to make the simplest area chart I could devise. If you want to jump straight to “the answer,” seethe complete JavaScript.
D3.js is not a chart library. It is a chartpartslibrary. The library feels like a mashup of SVG and data manipulation with some sugar sprinkled on top. While immensely flexible, the flexibility comes at the cost of complexity. Let’s dive in.
To build the chart, we need: data, an SVG container, margins, an X axis, a Y axis, the area shape itself, and some CSS to make it look pretty.
Data
We’re not going to mess with TSV or CSV loaders or any of the callback stuff. Here is the data, plain and simple.
vardata=[{x:0,y:10, },{x:1,y:15, },{x:2,y:35, },{x:3,y:20, },];
SVG
D3 uses SVG (Scalable Vector Graphics) to draw its shapes. It’s possible to
create a new<svg>
tag on the fly, but I added the following to the HTML
source code.
<svgid="area"/>
Margins
Charts in D3 have no margins, but the primary D3 author frequently talks about
definingconventional margins. The idea
is to make some margins and define an SVG group (i.e. theg
tag) that is
set to those margin boundaries. The code only considers the group tag as the
drawable area.
varmargin={top:20,right:20,bottom:40,left:50},width=575-margin.left-margin.right,height=350-margin.top-margin.bottom;
Axes
To draw data in a scalable way, D3 needs to be able to map the data (e.g., x=0, y=10) to a pixel position. We must take the X data and set it on the axis so that the maximum X value (i.e. 3) matches the pixel width of the chart area. Because D3 is so flexible, it means that X and Y must be defined independently.
In math class, you were probably taught that X is for the domain
and Y is for the range. Unfortunately, D3 uses domain/range terms to apply to
axes too. We have to think about the X data (0 - 3) as the domain, and the
chart horizontal dimension (0 -width
) as the range. The same kind of
thinking has to be applied for the Y axis as well (0 - 35 applied to the
chart vertical dimension).
You can think of thex
andy
variables as translator functions that take
a domain value and convert it to a pixel size.xAxis
andyAxis
are
indicating where the axes should go.
varx=d3.scale.linear().domain([0,d3.max(data,function(d) {returnd.x; })]).range([0,width]);vary=d3.scale.linear().domain([0,d3.max(data,function(d) {returnd.y; })]).range([height,0]);varxAxis=d3.svg.axis().scale(x).orient("bottom");varyAxis=d3.svg.axis().scale(y).orient("left");
Area
The area function transforms each data point like (2, 35) into information
that describes the shape. Each corresponds to an x position, an upper y
position,y1
, and a lower y position,y0
. The odd thing here is thaty0
is set to the constant ofheight
. This makes sense when you know that SVGs
are positioned relative to the upper left corner of the graphic. Any distance
“down” is a positive number, so a positiveheight
means the bottom of the
graphic.
vararea=d3.svg.area().x(function(d) {returnx(d.x); }).y0(height).y1(function(d) {returny(d.y); });
Putting it all together
So far, we have not done anything except define some data and functions. Now we need to put those functions to work.
varsvg=d3.select("svg#area").attr("width",width+margin.left+margin.right).attr("height",height+margin.top+margin.bottom).append("g").attr("transform","translate("+margin.left+","+margin.top+")");svg.append("path").datum(data).attr("class","area").attr("d",area);svg.append("g").attr("class","x axis").attr("transform","translate(0,"+height+")").call(xAxis);svg.append("g").attr("class","y axis").call(yAxis);
The variable definition ofsvg
grabs thesvg
tag with IDarea
and
adds a group tag,g
, to define the margins within the SVG. All the
drawing will happen inside thisg
tag.
The next section adds apath
. This is where the data and the area function
meet.It is the keystone of this entire example.D3 uses each data
point and passes it to thearea
function. Thearea
function translates
the data into positions on the path in the SVG. It will result in:
<pathclass="area"d="M0,214.28571428571428L168.33333333333331,171.42857142857142L336.66666666666663,0L505,128.57142857142858L505,300L336.66666666666663,300L168.33333333333331,300L0,300Z"/>
The last two sections adds the axes to the SVG. There isn’t much to say about them.
Make it pretty
In “Putting it all together”, I ignored the.attr("class", "area")
explanations. D3 can add any tag attributes withattr()
. I added someclass
attributes so that the graph can be styled. SVG uses different
properties than standard HTML tags, but the styling below gave
the graph its simple look.
svg{border:1pxsolid#dedede; }.axispath,.axisline{fill:none;stroke:#000;shape-rendering: crispEdges;}.area{ fill:#4ca3bd; }
Other charts
In this post, I covered the basics of making an area chart. In future posts, I will explain how to use other types of data and how to make stacked area charts. Stay tuned!