css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              @import "bourbon"
$data-color: CornflowerBlue
$grid-color: #ccc

#Graph
  font-size: em(13)

  path, line
    fill: none
  
  .marker
    fill: $data-color

  .tick line
    fill: none
    stroke: $grid-color
    stroke-width: 1
    shape-rendering: crispEdges

#visualisation-line
  fill: none
  stroke-linecap: round
  stroke-linejoin: round
  stroke-width: 3
  stroke: $data-color

            
          
!
            
              class TimeFormatter {

  static getDefault() {
    return d3.time.format.multi([
      // See https://github.com/mbostock/d3/wiki/Time-Formatting#format_multi
      // which is required for a time.scale()
      ['.%L', function(d) { return d.getMilliseconds(); }],
      [':%S', function(d) { return d.getSeconds(); }],
      ['%I:%M', function(d) { return d.getMinutes(); }],
      ['%I %p', function(d) { return d.getHours(); }],
      ['%a %d', function(d) { return d.getDay() && d.getDate() != 1; }],
      ['%b %d', function(d) { return d.getDate() != 1; }],
      ['%B', function(d) { return d.getMonth(); }],
      ['%Y', function() { return true; }]
    ]);
  }
}

const formatDate = d3.time.format('%Y-%m-%d');

function drawLineGraph (options, data) {
  const description = 'Visualisation using d3.js';

  /** Make it less verbose to access default margin values */
  const margin = Object.assign(options.chart.margin);

  /** Use @mbostock's margin convention - https://bl.ocks.org/mbostock/3019563 */
  const width = options.chart.width - margin.left - margin.right;
  const height = options.chart.height - margin.top - margin.bottom;

  const allDates = [];
  const allValues = [];

  let xScale;
  let yScale;
  let xAxis;
  let yAxis;
  let lineData;

  function prepareData(data) {
    data.forEach((entry) => {
      allDates.push(formatDate.parse(entry[0]));
      allValues.push(entry[1]);
    });
  }

  function defineScales() {
    xScale = d3.time.scale().range([0, width]);
    yScale = d3.scale.linear().range([height, 0]);
  }

  function defineAxes() {
    xAxis = d3.svg.axis()
      .scale(xScale)
      .orient('bottom')
      .tickPadding(10) // move tick text further away from tick lines
      .tickSize(10, 0)
      .ticks(5)
      .tickFormat(TimeFormatter.getDefault());
    yAxis = d3.svg.axis()
      .scale(yScale)
      .orient('left')
      .tickPadding(10) // move tick text further away from tick lines
      .tickSize(20, 0) // add space to the right of the y axis grid line (before the first marker)
      .ticks(6)
      .tickFormat((d) => { return `${d}%`; });
  }

  function defineLineData() {
    lineData = d3.svg.line()
      .x((d) => {
        let date = formatDate.parse(d[0]);
        return xScale(date);
      })
      .y((d) => {
        return yScale(d[1]);
      });
  }

  function defineScaleDomains(x, y) {
    /** Set the domain of the axes using min/max values */
    x.domain(d3.extent(allDates));
    /** Given it's a percentage value from 0% to 100%, we can directly set min/max */
    y.domain([0, 100]);
  }

  function renderGraph(options, data) {
    /**
     * Start rendering to the view
     * Note:
     *  - The styles set below are set as default. Styles should live in the graph stylesheet
     *  - Visual order is determined by the order an element gets drawn to the 'canvas'
     */
    const svg = d3.select(`#${options.chart.id}`)
      .append('svg')
      .attr({
        'width': options.chart.width,
        'height': options.chart.height,
        'xmlns': 'http://www.w3.org/2000/svg',
        'version': '1.1'
      });

    /** Roll the credits */
    svg.append('desc').html(description);

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

    const xAxisGroup = visualisation.append('g')
      .attr({
        'class': 'axis x',
        'transform': `translate(0, ${height})`
      })
      .call(xAxis);

    xAxisGroup.selectAll('line')
      .attr({'stroke': '#ccc'});

    visualisation.append('g')
      .attr({'class': 'axis y'})
      .call(yAxis);

    /** Add horizontal lines to the graph as reference points */
    visualisation.append('g')
      .attr({'class': 'grid'})
      .call(yAxis.tickSize(-width - margin.right, 0, 0).tickFormat(''))
      .selectAll('line')
      .attr({'stroke': '#ccc'});

    visualisation.append('path')
      .datum(data)
      .attr({
        'id': 'visualisation-line',
        'stroke-linejoin': 'round',
        'fill': 'none',
        'stroke-width': '1px',
        'stroke': '#000',
        'd': lineData
      });

    visualisation.selectAll('circle')
      .data(data)
      .enter()
      .append('circle')
      .attr({
        'class': 'marker',
        'r': options.chart.markerRadius,
        'cx': (d) => {
          let date = formatDate.parse(d[0]);
          return xScale(date);
        },
        'cy': (d) => {
          return yScale(d[1]);
        }
      });
  }

  prepareData(data);
  defineScales();
  defineAxes();
  defineLineData();
  defineScaleDomains(xScale, yScale);
  renderGraph(options, data);
}

const graphOptions = {
  chart: {
    margin: {
      top: 20,
      right: 30,
      bottom: 30,
      left: 70
    },
    width: 620,
    height: 280,
    id: 'Graph',
    markerRadius: 5
  }
};

const graphData = new Array();
for (let i = 0; i < 3; i++) {
  for (let y = 0; y < 11; y++) {
    graphData.push([`2016-${i+1}-${y+1}`, Math.round(Math.random() * 100 / 10) * 10]);
  }
}

drawLineGraph(graphOptions, graphData);

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console