Red Sift D3 Components

Bring data to life in your frontend Sifts

To bring the data computed by your Sift on the screen we provide you with a set of configurable D3 components to get started quickly with the visualization of your data. This list will grow over time, so make sure to check back every now and then.

The Red Sift D3 Components are following the D3 reusable chart convention which includes various ways for data to be displayed in an interactive chart. In this section, we are going to explore each of the components to give you an overview how and for which type of data to use them. You can play around with the components on your own with the provided Codepens. Try it, its fun bringing your data alive!

Components Reference:

This section contains documentation for the following libraries, which can be found on Github:

We also provide data visualization web components below, which hide the D3 interface and expose only a simple interface via HTML and Javascript. They have a ui- prefix to distinguish them from the libraries above which expose a D3 interface:

d3-rs-lines library

The d3-rs-lines library is one of Red Sift components that map your data-set to generate line charts. The library include different property that render the chart to support area fills, hovers and highlights.

Datum

The data structure used by the Red Sifts components are different for each component. The structure used by the lines library is shown below.

//A simple line chart structure

//Structure of the dataSet 
//l represent the x-axis and v is the y-axis 
let dataSet = [{l: 1 , v: 3},	 //this represent (1,3)
               {l: 4 , v: 7},		
               {l: 6 , v: 9}
							];

let  chart = d3_rs_lines.html();

d3.select('body')
	.datum(dataSet)
	.call()

Below shows the result of the simple line chart structure:

Showcasing the lines library

The showcase utilises the lines library to provide an interactive chart taking advantage of the diverse properties of the library.

Lines Library Properties

The lines library comes with a range of properties that provides customisation to the line chart. It allows the chart to change in colours, highlights values, animate or display info on hover.

The following shows a collection of properties that can be used with the line chart.

Parameters

PropertyDescriptionTransition
classedString Customise SVG by adding, removing and toggling of CSS classes.N
backgroundString, Number Change the background colour of the chart.Y
themeString Change the chart theme which includes 'light'(default) and 'dark'.Y
height, widthInteger Resize the height and width of chart. Default width: 420 pixels.Y
sizeInteger Resize the chart to a certain size changing both the width and height maintaining the default aspect ratio.Y
scaleNumber Scale the entire chart by the scaling value. Used to zoom the chart or compensate for high DPI displays when rasterized. Default scale: 1.0.Y
marginNumber Resize the chart margin inside of the SVG container. Default margin: 26 pixels.Y
insetNumber Resize the space inside the chart margin for the main chart element. This excludes items like legends.Y
styleString Custom CSS to inject into chartN
trimInteger Trim the datum array, use for slicing the data on the chart.N
minValue,maxValueNumber Sets the minimum and maximum Value range. Note that for log scales, minValue must be > 0.Y
minIndex ,maxIndexNumber Sets the minimum and maximum Index range. Note that for log scales, minIndex must be > 0.Y
tickCountIndex,tickCountValueNumber, String, Interval Function Hints at the number of ticks to set in the corresponding axis. Supports strings for example split time intervals when using Unix timestamp(or epoch time) Index values. Default tickCountIndex: 6N
tickMinorIndex, tickMinorValueNumber, String, Interval Function Hints at the number of minor ticks to set in the corresponding axis.N
tickFormatIndex, tickFormatValueString, Function Sets the formatting string or function for the ticks.N
tickDisplayIndex, tickDisplayValueString, Integer Customise all tick presentation logic with this function.N
curveString, Function, Interpolation function for the line. Standard functions excluding closed and open curves are usable by name e.g. 'curveStep'. If a function is supplied, it should implement custom curves. Default curve: 'curveCatmullRom'Y
symbol(Array of) String, Function Change the points connecting the lines into customised symbols or custom symbol typesN
symbolSizeNumber Resize the symbol to a specific size. Default size: 32Y
fillString, Array, Function If function, in addition to usual data, index parameters, a 3rd string parameter indicates the context - one of area, stroke, symbol, legendY
fillAreaOpacityUnit Number Fill the area of the graph to a certain opacityN
fillAreaBoolean, (Array of) Boolean Set the lines fill.N
fillStrokeBoolean, (Array of) Boolean Set the lines stroke.N
stackedBoolean Enable stacking. Default value: falseY
stackOffsetString, Function Shift the baseline of the chart to give more emphasis on the changing values using different offset properties.Y
stackOrderString, Function Stack the chart using different stack ordering properties.Y
animationString Change the animation interpolating between points. Parameters: reveal, value, default.Y
tipHtmlString, Function Add information to the tip of the chart. Parameters of the function are (d, i, s) where d is the data element, i is the index, s is the series of the data.Y
animateAxis, animateLabelsBoolean Set the animation of the axis and label. Default value: true.N
axisDisplayIndex,axisDisplayValueBoolean Set the axes to display. Default axisDisplayIndex: true, axisDisplayValue: false.N
axisPaddingValue,axisPaddingIndexNumber Set the padding size of the axis. Default axisPaddingValue: 8, axisPaddingIndex: 8.N
axisValueString Changes the axis label of value (on the y-axis) to the left or right. Default value: 'left'.N
highlightIndex(Array of)Number, Function Highlight a particular or an array of IndexY
legend(Array of)String, Number Add a legend for the lines in the chart.N
legendOrientationString Position the legend, positions include top, bottom, left, right or voronoi. Default orientation: 'bottom'Y
legendOrientation('voronoi')String Position the legend in an area containing the least number of intersecting lines.N
voronoiAttractionNumber -1...0...1 Use when legendOrientation set to voronoi. Specifies the attraction of the label to the data line. 0 implies no dragging, -1 pushes the labels away. Default value: 0.33Y
gridIndex, gridValueBoolean Add guidelines for Index or Value. Default gridIndex: false, gridValue: true.N
labelTimeString, Function Interpret the Index value from timestamp and format it using string specifiers or the supplied function. 'multi' (string specifier) smartly displays the time and use the UTC format.N
languageString Change the language format of the chart affecting digit, currency and time formats.N
onClickFunction Handler for a click event on a data series.N

Examples

This section provide a quick look at the properties available and how they are used.

View @redsift/d3-rs-lines collection on Codepen

d3-rs-squares library

The d3-rs-squares is a library which focuses on providing insight from your data in the form of square matrices. The library can easily generate either a co-occurrence matrix or a calendar chart. The calendar chart supports only Unix time stamp data set.

Datum

The squares library contains two different data structure which are used to produce matrix or calendar chart.

The simple example below give an example of how the matrix chart is structured.

//A simple matrix structure

//Structure of the dataSet 
//x represent the x-axis, y represent the y-axis and z the colour intensity
let dataSet = [
               {x: 1 , y: 3, z:10},  //this represent the x: column y: row z: colour 
               {x: 4 , y: 7, z:1},   
               {x: 6 , y: 9, z:5}
              ];

let  chart = d3_rs_squares.html();

d3.select('#chart')
  .datum(dataSet)
  .call(chart)

The result of the above dataSet is given below.

The calendar data structure is different to matrix, where it only support UNIX time stamp data. The type by default is set to matrix thus when using calendar you will need to change the calendar property.

The simple example below give an of how the data for calendar chart need to be structured.

//A simple calendar chart structure

//Structure of the dataSet 
//Calendar dataset takes Unix timestamp as parameter for 'd'
//'v' is the square colour intensity 
let dataTime = [  
      {d: 1462057200000, v: 10},
      {d: 1462402800000, v: 5},
      {d: 1464822000000, v: 15}
    ];

let  chart = d3_rs_squares.html()
                          .type('calendar.days'); //the type need to be set for calendar property since by default it is set to matrix

d3.select('#chart')
  .datum(dataTime)
  .call(chart)

The above calendar chart example result is given below:

Showcasing the squares library

The showcase utilises the squares library to provide an interactive chart taking advantage of the diverse properties of the library.

Squares library properties

The squares library has a variety of properties that allows customisation for the square chart. The square chart can be modified by change in colour, range in calendar dates or squares colour intensity.

Parameters

NameUsed InDescriptionTransition
classed*SVG custom classN
width, height, size, scale*Integer SVG container sizesY
style*String Custom CSS to inject into chartN
color*String Color palette for the data. Available options from d3-rs-theme e.g. 'blue','green','aqua',...Y
theme*String 'light' (default) or 'dark' as described in d3-rs-theme
inset*Integer, Object Provide additional margin for axis with long keys. Expected object structure {top: 0, bottom:10, left:10, right:0}
zfieldmatrix.*String When z field is an object this parameter gives you the ability to use the value under a different key e.g. for {x:'',y:'',z:{prop1:''}} to use the value of the prop1 key pass the name of the key 'prop1' to the parameter
cellSize*Integer Get or override calculated size of cells
type'calendar.days', 'calendar.hours', 'matrix.cooc', 'matrix'(default)
minDate'calendar.days'Timestamp Override the earliest day of the datasetY
maxDate'calendar.days'Timestamp Override the latest day of the datasetY
nice'calendar.days'Boolean (deault: yes) Extend range of calendar to display whole monthsN
monthSeparation'calendar.days'Boolean (deault: yes) Add extra space between monthsN
startingcalendar.*String First day of the week. Default is 'timeSunday' Available options: ('timeMonday', 'timeTuesday', ...) or the utc counterparts: ('utcMonday', 'utcTuesday', ...) based on the d3-time package
rangeIndex, rangeValuematrixString, Function, Array ranges from d3-time#ranges (Milliseconds not supported) Custom ranges need to follow the d3-time#range paradigm. If an array is supplied first expected element is the range function and second a cardinality override of the range unit e.g. [d3.timeYear, 2] for a range of 2 years
intervalIndex, intervalValuematrixString, Array intervals from d3-time#intervals (Milliseconds not supported). For custom intervals an array is expected with the interval and range functions following the paradigm in d3-time e.g. [timeHour, timeHours]
onClickFunction handler for a click event on the data series

Examples

This section provide a quick look at the properties available and how they are used.

View @redsift/d3-rs-squares collection on Codepen

d3-rs-geo library

The d3-rs-geo library provide a TopoJSON map in an SVG constainer. TopoJSON is an extension of GeoJSON that encodes topology. The d3-rs-geo library enables linking points of interest, projection and zoom.

Datum

Datum can be one of:

  1. String representing the URL to load the TopoJSON file for the map from
  2. Object representing the TopoJSON itself
  3. Object with key url (URL to load the TopoJSON file) and optionally the keys points and links

The simple example below represent the TopoJSON datum of the world. The datum uses the object with key url of the TopoJSON link.

//simple example of the topoJSON Datum
var geo = d3_rs_geo.html();

    d3.select('#elm')
      .datum({ url: 'https://static.redsift.io/thirdparty/topojson/examples/world-50m.json' }) //world topoJSON
      .call(geo);

The result of the simple example:

Showcasing the geo library

The example below uses a variety of properties included in the geo library to provide links between countries using links. The showcase represent link from London Heathrow Airport, UK to different part of the world. A convenient way to show the airport route of different journey travelled by an individual.

Parameters

PropertyDescriptionTransition
classedString SVG custom classN
width, height, size, scaleInteger SVG container sizesY
backgroundString Change the colour of the SVG backgroundY
themeString Change the graph theme which include 'light'(default) and 'dark'.Y
marginNumber Change the margin inside of the SVG container.Y
graticuleNumber Opacity of the graticule (line grid). Parameter range between 0 and 1.N
projectionString Change projection view of the world map. Default set to geoPattersonY
projectionScaleNumber Change the projection scale of the world map.Y
interruptedBoolean Enabled clipping for interrupted projections. Default set to true.N
geometryString Set the country geometry Parameters land;display the entire country geometry , states; display each state of the country, countries; display each countries.N
fillString Change the land filling colour. Parameter colour name, rgb colour or hex colour.Y
points(Array of)Number Add points on the map using decimal expression of [ Longitude, Latitude ].N
pointsDisplayFunction, String Supply custom symbol of the plotted points i.e. object that implements a draw function or supply a totally custom reusable component via the pointsDisplay property. Default set to symbolWye.N
links(Array of)Number Links each points. Parameter include an arrays of points connecting the link.Y
linksDisplayFunction, String Supply custom presentation to the dashed line.
zoomNumber Zoom into the map. Default set to 1.0.Y
zoomX, zoomYNumber Zoom into the map at x-coordinate (zoomX) and Y-coordinate (zoomY).Y
onClickFunction Handler for a click event on a data series.N

Examples

The examples showcase the property of the library.

d3-rs-bars library

The d3-rs-bars library generate an interactive bar chart from your data-set that can be stacked or unstacked series. The library supports a variety of properties that includes hovers and highlights.

Datum

The structure of the datum is similar to d3-rs-lines datum which can include just a simple datum array or can be customised using Index and Value which can support epoch time data.

1 ) The example below is using a simple datum customising just the bar size.

//A simple bar chart structure

let chart = d3_rs_bars.html();

//datum just include an array with the data
d3.select('body')
  .datum([300,400,1000,700,500]) 
  .call(chart);

The preview of the above datum.

  1. The datum can be customised using the Index and Value. Value ("V") specify the length of the bar chart and Index ("I") is used to label the bar. The example below uses String to label "l" but Number or Epoch time (Example 4) could also be used.
//A simple bar chart structure 2

let chart = d3_rs_bars.html();

//datum using Index and Value to customise the bar
  let data = [{"l":"Gas","v":59},{"l":"Water","v":22},{"l":"Oil","v":30}];

d3.select('body')
  .datum(data) 
  .call(chart);

The preview of the above datum.

  1. The datum also support a series of data for stacked or unstacked bar chart. By default the series data are set to stack and can be changed to unstacked using the stacked property set to false.
//A simple bar chart structure 3

let chart = d3_rs_bars.html();

//datum using Index and Value using data series and by dafault it is stacked
let data = [{"l":2,"v":[5,4,2]},{"l":4,"v":[2,2,4]},{"l":1,"v":[3,1,2]}]

d3.select('body')
  .datum(data) 
  .call(chart);

The preview of the above datum.

  1. The datum can also supports epoch time data-set which can be used instead of an Integer or a String. This provide additional customisation to your bar chart if you want to include month of a year or day of a week to support your chart.
//A simple bar chart structure 4

let chart = d3_rs_bars.html()
                      .labelTime('%a'); //format the epoch time using string specifiers

//datum using epoch time dataset 
let data = [{"l":1466511212000,"v":[5,4,2]},{"l":1466856812000,"v":[2,2,4]},{"l":1466684012000,"v":[3,1,2]}]

d3.select('body')
  .datum(data) 
  .call(chart);

The preview of the above datum.

Showcasing the bars library

The showcase is a re-implementation of Research Excellence Framework (REF) scores from giCentre using the d3-rs-bars library.

Bars library properties

The bars library includes a variety of properties that can customise the bar chart. The library comprise of the hovers, highlight, stacked and tick properties.

Parameters

PropertyDescriptionTransition
classedString Customise SVG by adding, removing and toggling of CSS classes.N
backgroundSting, Array, Function Change the background colour of the SVG container. Background colour can be set using a colour name, rgb or hex value.Y
themeString Customise the chart theme including 'light'(default) and 'dark'.Y
fillSting, Array, Function Change the bar chart colour using a String which can take colour name, rgb or hex value as an argument. Using an Array of custom colours or use 'global' to generate random colour or supply a custom function.Y
styleString Custom CSS to inject into chart.N
width, heightInteger Resize the height and width of the chart. Default width: 420 pixels.Y
sizeInteger Resize the chart to a certain size changing both the width and height maintaining a default aspect ratio.Y
scaleInteger Scale the entire chart by the scaling value. Used to zoom the chart or compensate for high DPI displays when rasterized. Default scale: 1Y
marginNumber Change the chart margin inside of the SVG container. Default margin: 26.Y
insetNumber Resize the space inside the chart margin for the main chart element. This excludes items like legends.Y
highlight(Array of)Integer Highlight an array of value or a particular value.Y
minValue,maxValueNumber Set the minimum and maximum Value scale range. Note that for log scales, minValue must be > 0.Y
legend(Array of) String Add legends to the chart where array of String can be supply for multiple bar chart.N
legendOrientationString Position the legend, positions include top, bottom, left or right. Default orientation : 'bottom'Y
orientationString Set the orientation of the labels. Default oriented : left. Parameters include right,left,top and bottom.Y
rotateValue,rotateIndexInteger Rotate the Index or Value ticks in degree where positive degree represent clockwise rotation and negative degree anticlockwise rotation. Default rotation : 0.Y
labelTimeString Interpret the label as a millisecond epoch and format it using specified string.N
barSizeInterger Change the size of the bar elements. Positive value set the absolute value in pixels. Negative values specify the scale relative to space between ticks. i.e. -0.5 will set the bar size to 50% of the width between the ticks. Default size set to 6.Y
tickDisplayValueString, Integer Rename all tick to a single argument taking a String or a Number.N
labelString Use the same labels for value using a String or an Integer.N
tickFormatValue, tickFormatIndexString, Function Set the formatting string or function for the ticks.N
tickCountValue, tickCountIndexNumber, String, Interval Function Hints at the number of ticks to set in the corresponding axis. Supports strings for example split time intervals, apply when using epoch time format. Default tickCountIndex: 6N
displayTipInteger Position the tip display on the bar chart on hovering.Y
displayHtmlString,Function Customise the tip info. Function parameters include (d,i), d represent data and i the dataset.N
stackedBoolean Enable bar chart to stack onto each other.Y
valueFunction Generate a bar chart from selecting an object values carrying the data to generate the bar chart.N
gridBoolean Enable grid to display on the chart. Default: true.N
logValueInteger Alter the grid spacing for value.Y
languageString Change the language format of the chart affecting digit, currency and time formats.N

Examples

The examples showcase the property of the library.

ui-rs-radial-chart library

This chart can be used to show data over time in a radial fashion, e.g. your monthly expenses on taxis over a year. It is implemented as a custom element (which is one corner stone of web components.

To include the library add the following lines for the CSS and the Javascript to your web page:

<link rel="stylesheet" href="https://static.redsift.io/reusable/ui-rs-radial-chart/latest/css/ui-rs-radial-chart.min.css">

<script src="https://static.redsift.io/reusable/ui-rs-radial-chart/latest/js/ui-rs-radial-chart.umd-es2015.min.js"></script>

After the library is included use it like so:

<rs-radial-chart>
  <div id="chart"></div>
  <div id="legend"></div>
</rs-radial-chart>

The d3-rs-radial-chart element contains two DIVs for the chart itself and a legend. If you do not want a legend simply remove the DIV. To fill the chart with live add some data to it with Javascript:

let chart = document.querySelector('rs-radial-chart');

if (chart) {
  // Setup radial chart via public API
  chart.data = _dummyData(200);

  var count = 0;
  setInterval(() => {
    chart.data =  _dummyData((Math.random() * 400) + 20);
  }, 2500);
}

// Dummy data generator - creates an array with 12 objects, one for each month,
// with the following form:
// [ {
//      name: 'Jan',
//      value: '23',
//      color: () => { return '#0000ff'; },
//      classed: 'stripe'
//   }, {
//      name: 'Feb',
//      value: '173',
//      color: () => { return '#00ff00'; },
//   },
//   ...
// ]
// The generator uses utility functions provided by RedsiftUI for the handling
// of months.
function _dummyData(range) {
  let color = d3.scale.category20(),
      r = Redsift.Lang.localShortMonths();
  r = r.concat(Redsift.Lang.localShortMonths(), Redsift.Lang.localShortMonths());
  return r.map((m, i) => {
    let v = Math.random() * range;
    return {
      name: m,
      value: v,
      color: () => { return color(v); },
      classed: (i !== 1) ? undefined : 'stripe'
    };
  }).filter((d, i) => { return i < 12; });
}

The data structure expected by the chart is a simple array with an object for each month containing a name, value, color and optional classed value. The classed value can be set to a class name which will be applied to the visual data cone of the respective month. This allows you e.g. to highlight a month when it is over a certain budget limit. color is a function returning a color in hex. Here is an example of the structure:

let data = [{
    name: "Jan",
    value: 3.6732592034888905,
    color: () => { return '#00ff00'; }
  }, {
    name: "Feb",
    value: 3.3835721480313685,
    color: () => { return '#00ff00'; },
    classed: "stripe"
  }, {
    name: "Mar",
    value: 46.90614320865888,
    color: () => { return '#00ff11'; }
  }, {
    name: "Apr",
    value: 16.262593631395912,
    color: () => { return '#00ff22'; }
  }, {
    name: "May",
    value: 53.40171839979518,
    color: () => { return '#00ff33'; }
  }, {
    name: "Jun",
    value: 15.899117927917139,
    color: () => { return '#00ff44'; }
  }, {
    name: "Jul",
    value: 6.650584346480011,
    color: () => { return '#00ff55'; }
  }, {
    name: "Aug",
    value: 26.689381547140503,
    color: () => { return '#00ff66'; }
  }, {
    name: "Sep",
    value: 34.29461737322482,
    color: () => { return '#00ff77'; }
  }, {
    name: "Oct",
    value: 26.4320733402228,
    color: () => { return '#00ff88'; }
  }, {
    name: "Nov",
    value: 51.88087153647562,
    color: () => { return '#00ff99'; }
  }, {
    name: "Dec",
    value: 54.6380052855129,
    color: () => { return '#00ffaa'; }
  }];

ui-rs-schedule

The ui-rs-schedule element allows you to create an SVG-based schedule for your visualization. It is implemented as a custom element (which is one corner stone of web components.

To include the library add the following lines for the Javascript to your web page:

<script src="https://static.redsift.io/reusable/ui-rs-schedule/latest/js/ui-rs-schedule.umd-es2015.min.js"></script>

Afterwards you can embed the element into your web page:

<rs-schedule></rs-schedule>
var data = [{
  "start": Date.parse("2016-04-13T14:30:00+01:00")
}, {
  "end": Date.parse("2016-04-13T18:30:00+01:00")
}, {
  "status": "confirmed",
  "summary": "Confirmed overlap event",
  "self": true,
  "start": Date.parse("2016-04-13T16:30:00+01:00"),
  "end": Date.parse("2016-04-13T18:30:00+01:00")
}, {
  "status": "tentative",
  "summary": "Tentative event",
  "self": false,
  "start": Date.parse("2016-04-13T15:00:00+01:00"),
  "end": Date.parse("2016-04-13T16:00:00+01:00")
}, {
  "status": "proposed",
  "summary": "Suggested event of some significant length",
  "self": false,
  "start": Date.parse("2016-04-13T16:00:00+01:00"),
  "end": Date.parse("2016-04-13T17:00:00+01:00")
}, ];

var chart = document.querySelector('rs-schedule');
chart.width = 350;
chart.data = data;

The element's width is set via the width attribute. The start and end of the displayed schedule is configured via the first two elements of the data array, with the start and end property respectively. The following elements are interpreted as schedule entries. Each is configured via these properties:

  • status: Can be one of confirmed, tentative and proposed and determines the color of the event
  • summary: Displays a short description of the event
  • start: The start date/time of the event
  • end: The end date/time of the event
  • self: Highlights the event with a symbol on the right