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 includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

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

              
                #Graph
              
            
!

CSS

              
                @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

              
            
!

JS

              
                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

Console