Skip to content

Instantly share code, notes, and snippets.

@ColinEberhardt
Created May 15, 2019 15:55
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ColinEberhardt/e76cdaef85d697ef0b090a8e82ca95be to your computer and use it in GitHub Desktop.
Line / Area Chart
license: mit

This example demonstrates how to render a simple Cartesian chart with a line and an area series. The chart is constructed from the following components:

  • A Cartesian chart, with linear scales for x and y, is used to render the plot area, axes and labels.
  • The data is rendered via a line series and an area series, these are combined into a single series using the multi series component.
  • A gridlines component is also added to the multi series.
  • The extent utility function is used to calculate the domain for the x and y scale, with padding applied to the y scale.

forked from ColinEberhardt's block: Line / Area Chart

<!DOCTYPE html>
<!-- include polyfills for custom event, Symbol and Custom Elements -->
<script src="https//unpkg.com/babel-polyfill@6.26.0/dist/polyfill.js"></script>
<script src="https//unpkg.com/custom-event-polyfill@0.3.0/custom-event-polyfill.js"></script>
<script src="https//cdnjs.cloudflare.com/ajax/libs/document-register-element/1.8.0/document-register-element.js"></script>
<!-- use babel so that we can use arrow functions and other goodness in this block! -->
<script src="https//unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https//unpkg.com/d3@5.5.0"></script>
<script src="https//unpkg.com/d3fc@14.0.1"></script>
<style>
body {
font: 16px sans-serif;
}
.chart {
height: 480px;
}
.line {
stroke: purple;
}
.area {
fill: lightgreen;
fill-opacity: 0.5;
}
</style>
<div id='simple-chart' class='chart'></div>
<script type='text/babel'>
// create some test data
var data = d3.range(50).map(d => ({
x: d / 4,
y: Math.sin(d / 4),
z: Math.cos(d / 4) * 0.7
}));
var yExtent = fc.extentLinear()
.accessors([d => d.y, d => d.z])
.pad([0.4, 0.4])
.padUnit('domain');
var xExtent = fc.extentLinear()
.accessors([d => d.x]);
// create a chart
var chart = fc.chartSvgCartesian(
d3.scaleLinear(),
d3.scaleLinear())
.yDomain(yExtent(data))
.yLabel('Sine / Cosine')
.yOrient('left')
.xDomain(xExtent(data))
.xLabel('Value')
.chartLabel('Sine/Cosine Line/Area Chart');
// create a pair of series and some gridlines
var sinLine = fc.seriesSvgLine()
.crossValue(d => d.x)
.mainValue(d => d.y);
var cosLine = fc.seriesSvgArea()
.crossValue(d => d.x)
.mainValue(d => d.z);
var gridlines = fc.annotationSvgGridline();
// combine using a multi-series
var multi = fc.seriesSvgMulti()
.series([gridlines, sinLine, cosLine]);
chart.plotArea(multi);
// render
d3.select('#simple-chart')
.datum(data)
.call(chart);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment