Interactive Line Chart D3.js v5

Shivika K Bisen
The Startup
Published in
3 min readJun 9, 2020

Written by Shivika K Bisen, Yashaswini Joshi and Vanya Procopovich

D3.js is a JavaScript library for producing dynamic data visualizations on the website. It makes use of Scalable Vector Graphics(SVG), HTML, and CSS. This article is about creating interactive line charts with D3.js. We used the v5 version of D3.js. Line charts are an excellent way to visualize time series data.

Here we will learn through an example of the USA obesity story. In our visualization, we tried to create a visualization structure similar to Martini's glass style. We have tried to visualize US obesity through different visualization techniques like Dorling cartogram, Scatter plot, etc. This article deals with the line chart part of the visualization.

Dataset

We used the data from the Center for Disease Control and Prevention’s (CDC) Division of Nutrition, Physical Activity, and Obesity. The dataset includes data from the Behavioral Risk Factor Surveillance System for each US state. For this visualization we considered the following variables: Break out, Break out the category, Locationabbr, Locationdesc, Year, and Average Data value. There are 9632 data instances. The obese population is defined as one with BMI > 30.

In the above animation when we click on the states, we get interactive line charts for each breakout category (Age group, race/ Ethnicity, Education attained, Gender, Household income). Breakout categories are:

  • Age Group: 18–24 yr, 25 -34 yr, 35–44 yr, 45–54 yr, 55–64 yr, 65 and above
  • Race/Ethnicity: American Indian, Asian, Black, Hispanic, Multiracial, Other, White
  • Household Income: College graduate, H.S or G.E.D, Less than H.S, Some post-H.S
  • Education attained: Less than $15K, $15K-$24K, $25K-$34K ,$35K-$49K, $50K and more
  • Gender: Female, Male

Encoding Specification:

  • X-axis: Year (Quantitative)
  • Y-axis: Obesity rate (Quantitative)
  • Color: Breakout categories (Nominal)
  • Tooltip: text annotation of Percentage of obesity prevalence of that year.

Step 1: Create functions

In the below code, we created two functions called:

getGraphsForState(state, groupName, data) fetches the data values related to state and the groupName (breakout category) passed to that function.

getAllData(data) fetches data related to location description, category, and category_value.

Step 2: Start Creating function for drawing line chart

In the drawLineChart(state, groupName)function, we are defining variables x and y using d3.scaleTime()and d3.scaleLinear() respectively to scale x and y-axis. We created a variable line using d3.line. a line generator. Sets x accessor for the line as year using .x(d=>x(d.year)) and .y(d=>y(d.obesity)) sets y accessor for the line obesity rate

Step 3: Draw base

Now we, select our SVG element and provide it with some styling. We define a constant chartID to display the line chart for a particular state and groupName(breakout category).

Step 4: Read the data

Read the data using d3.csv('').then() to render the data. We call the function “getGraphsForState”. category is breakout. For instance for groupName Age category is 18–24 year.

Step 5: Draw header and Legends

The below code shows how to draw header and legend for groupName(breakout category). Here'g' groups all the SVG elements together.

Step 6: Draw Path

We now draw a line for each data point. Here .attr("d",function(d){return line(d.values);})gets us data point stored in d.values and .style("stroke",function(d){return color(d.name);})" gives us a line with color encoded for each breakout category.

Step 7: Mouse interactivity

We create a Tooltip handler using a variable mouseG (black vertical line) and mousePerLine (intersection point). mousePerLine has two attributes i.e. circle and text. We input the attribute calledtransform that updates data point in mousePerLine.append("text")

In mouseG (vertical line) we have embedded event handling functions. We are using mouseover (when the mouse is over selected SVG element, then we see the tooltip), mousemove (when we brush through the SVG element the data point updates in the tooltip), mouseout (when we take out the mouse of the line chart, tooltip disappears). return "translate("+ mouse[0]+","+ pos.y+”)”returns the position of SVG for mouse interactivity.

D3.js interactive charts are fun . You can check the whole code for line chart here: https://github.com/sbisen/d3-obesity-usa/tree/master/d3-playground/modules/line-chart.

The whole project can be found in https://github.com/sbisen/d3-obesity-usa

Part 2: Interactive Dorling Cartogram with Scatter plot D3.js

Reference:

--

--

Shivika K Bisen
The Startup

Gen AI/ML, Data Scientist | University of Michigan Alum | Generative AI, Recommendation & Search & NLP, Predictive models. https://sbisen.github.io/