Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <nav class="navbar navbar-default navbar-inverse">
 <div class="container">
  <span class="navbar-brand">D3 Line Chart</span>
 </div>
</nav>

<div class="container">
 <div id="selections" class="row">
  <div class="col-md-4">
   <div id="slider-div">
    <label>
       Date:
       <span id="dateLabel1">12/05/2013</span> 
       -
       <span id="dateLabel2">31/10/2017</span>
    </label>
    <div id="date-slider"></div>
   </div>
  </div>
  <div class="col-md-4">
   <select id="coin-select" class="form-control">
    <option selected value="bitcoin">Bitcoin</option>
    <option value="ethereum">Ethereum</option>
    <option value="bitcoin_cash">Bitcoin Cash</option>
    <option value="litecoin">Litecoin</option>
    <option value="ripple">Ripple</option>
   </select>
  </div>
  <div class="col-md-4">
   <select id="var-select" class="form-control">
    <option selected value="price_usd">Price in dollars</option>
    <option value="market_cap">Market capitalization</option>
    <option value="24h_vol">24 hour trading volume</option>
   </select>
  </div>

  <div class="row">
   <div class="col-md-12">
    <div id="chart-area"></div>
   </div>
  </div>
 </div>
</div>
              
            
!

CSS

              
                body {
   background: #333;
   color: white;
}

#chart-area {
  overflow: hidden;
  max-width: 800px;
  max-height: 500px;
  height: auto;
  margin: auto;
 
  svg {
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 100%;
    height: auto;
     
     text {
        fill: white;
     }
  }
}

.axis {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #666;
  stroke-width: 2px;
  shape-rendering: crispEdges;
}

.overlay {
  fill: none;
  pointer-events: all;
}

.focus circle {
  fill: none;
  stroke: #ddd;
  stroke-width: 3px;
}
  
.hover-line {
  stroke: #aaa;
  stroke-width: 2px;
  stroke-dasharray: 3,3;
}

#selections .col-md-4 {
  padding-top: 10px;
  padding-bottom: 10px;
}

.line {
  fill: none;
  stroke-width: 3px;
  stroke: steelblue;
}
              
            
!

JS

              
                /*
 * This pen has been build while participating in the D3.js course of Adam Janes on Udemy
 * https://www.udemy.com/masteringd3js
 */

let dataType = 'price_usd'
let currency = 'bitcoin'
let data = null
let rawData = null
let range = [0, 0]

const dataTypeCaptions = {
  'price_usd': 'US Dollar',
  'market_cap': 'Market capitalization',
  '24h_vol': 'Trading Volume'
}

const margin = { left: 80, right: 100, top: 50, bottom: 100 }
const totalHeight = 500
const totalWidth = 800
const height = totalHeight - margin.top - margin.bottom
const width = totalWidth - margin.left - margin.right

const slider = $('#date-slider')

const svg = d3
 .select('#chart-area')
 .append('svg')
 .attr('width', totalWidth)
 .attr('height', totalHeight)
 .attr('viewBox', `0 0 ${totalWidth} ${totalHeight}`)

const g = svg
 .append('g')
 .attr('transform', `translate(${margin.left}, ${margin.top})`)

// Time parser for x-scale
const parseTime = d3.timeParse('%d/%m/%Y')
// For tooltip
const bisectDate = d3.bisector(d => d.year).left

// Scales
const x = d3.scaleTime().range([0, width])
const y = d3.scaleLinear().range([height, 0])

const formatSi = d3.format('.2s')
function formatAbbreviation(x) {
  const s = formatSi(x)
  switch (s[s.length - 1]) {
    case "G":
      return s.slice(0, -1) + 'B'
    case "k": 
      return s.slice(0, -1) + 'K'
    default:
      return s
  }
}

// Axis generators
const xAxisCall = d3.axisBottom().ticks(4)
const yAxisCall = d3
 .axisLeft()
 .ticks(6)
 .tickFormat(d => formatAbbreviation(d))

// Axis groups
const xAxis = g
 .append("g")
 .attr("class", "x axis")
 .attr("transform", "translate(0," + height + ")")

const yAxis = g.append("g").attr("class", "y axis")

// Y-Axis label
const yLabel = yAxis
 .append("text")
 .attr("class", "axis-title")
 .attr("transform", "rotate(-90)")
 .attr("y", 6)
 .attr("dy", ".71em")
 .style("text-anchor", "end")
 .attr("fill", "#5D6971")

// Line path generator
const line = d3
 .line()
 .x(d => x(d.year))
 .y(d => y(d.value))

const dataUrl = "https://raw.githubusercontent.com/adamjanes/udemy-d3/master/06/6.10.1/data/coins.json"

const graphLine = g
  .append("path")
    .attr("class", "line")
    .attr("fill", "none")
    .attr("stroke", "grey")
    .attr("stroke-with", "3px")
 

$("#coin-select").change(function() {
  currency = $(this).val()
  update()
})

$("#var-select").change(function() {
  dataType = $(this).val()
  update()
})

const $dateLabel1 = $("#dateLabel1")
const $dateLabel2 = $("#dateLabel2")

const getSelectedData = () => rawData[currency]

const update = () => {
  
  const allSelectedData = getSelectedData()
  data = allSelectedData
    .filter((d, i) => i >= range[0] && i <= range[1])
    .map(d => ({
      year: parseTime(d.date),
      value: +d[dataType],
    }))

  slider.slider({
    max: allSelectedData.length - 1,
    min: 0,
    step: 1,
    range: true,
    values: range,
    slide: (event, ui) => {
      range = ui.values
      update()
    },
  })
 
 $dateLabel1.text(allSelectedData[range[0]].date)
 $dateLabel2.text(allSelectedData[range[1]].date)

  // Set scale domains
  x.domain(d3.extent(data, d => d.year))
  y.domain([
    d3.min(data, d => d.value) / 1.005,
    d3.max(data, d => d.value) * 1.005
  ])

  // Generate axes once scales have been set
  xAxis.transition().call(xAxisCall.scale(x))
  yAxis.transition().call(yAxisCall.scale(y))
  
  yLabel.text(dataTypeCaptions[dataType])
 
  graphLine
    .transition()
    .ease(d3.easeLinear)
    .duration(100)
    .attr("d", line(data))
};

function mousemove() {
  const x0 = x.invert(d3.mouse(this)[0])
  const i = bisectDate(data, x0, 1)
  const d0 = data[i - 1]
  const d1 = data[i]
  const d = x0 - d0.year > d1.year - x0 ? d1 : d0;
  focus.attr("transform", `translate(${x(d.year)},${y(d.value)})`)
  focus.select("text").text(d.value)
  focus.select(".x-hover-line").attr("y2", height - y(d.value))
  focus.select(".y-hover-line").attr("x2", -x(d.year))
}

/******************************** Tooltip Code ********************************/
const focus = g
  .append("g")
  .attr("class", "focus")
  .style("display", "none")

focus
  .append("line")
  .attr("class", "x-hover-line hover-line")
  .attr("y1", 0)
  .attr("y2", height)

focus
  .append("line")
  .attr("class", "y-hover-line hover-line")
  .attr("x1", 0)
  .attr("x2", width)

focus.append("circle").attr("r", 7.5)

focus
  .append("text")
  .attr("x", 15)
  .attr("dy", ".31em")

g
  .append("rect")
  .attr("class", "overlay")
  .attr("width", width)
  .attr("height", height)
  .on("mouseover", () => focus.style("display", null))
  .on("mouseout", () => focus.style("display", "none"))
  .on("mousemove", mousemove)

 /******************************** Tooltip Code ********************************/

d3.json(dataUrl).then(response => {
 rawData = response
 const data = getSelectedData()
 range = [0, data.length - 1]
 update()
})

              
            
!
999px

Console