1.1.12 • Published 8 years ago

react-linechart v1.1.12

Weekly downloads
801
License
MIT
Repository
github
Last release
8 years ago

React Linechart

Highly customizable line charts using React! Check the Live Demo and follow along the tutorial.

  1. Why
  2. Installation
  3. Usage
  4. Properties Table
  5. Tooltips
  6. Derived Charts
  7. Parsers
  8. isDate
  9. Improvements

Why

I always felt frustrated with the libraries out there which aim to implement this simple visualization. Many would lack basic features (such as adding multi lines or changing line colors) or would be extremely low-level (think d3). Built on top of d3, react-linechart provides necessary customization without losing simplicity.

Installation

npm install react-linechart --save

Usage

Add Line Charts with minimum configuration:

import React, { Component } from 'react';
import LineChart from 'react-linechart';
import '../node_modules/react-linechart/dist/styles.css';

export default class App extends Component {
	render() {
		const data = [
			{									
				color: "steelblue", 
				points: [{x: 1, y: 2}, {x: 3, y: 5}, {x: 7, y: -3}] 
			}
		];
		return (
			<div>
				<div className="App">
					<h1>My First LineChart</h1>
					<LineChart 
						width={600}
						height={400}
						data={data}
					/>
				</div>				
			</div>
		);
	}
}

This component is an attempt to simplify the rendering of a basic Line Chart by exposing many props that are commonly used. I realize it is very hard to encompass every use case, so I put an effort in making this especially pleasant to work with continuous values of numbers and dates.

The only mandatory prop is data - an array of objects describing the lines that will be rendered on screen. The typical line object follows this structure:

{
	id,
	name,
	color,
	points: [ { x, y } ]
}

Where id is an identificator for the line, name is a name for the line, color is a color for the line and points are an array of { x, y } objects representing the data. It would be particularly annoying if we need to parse our data to this format, so I provided a handful of parser functions that hopefully will meet most data formats commonly out there.

Properties Table

PropertyTypeDefaultDescription
idStringnoneUnique ID for the visualization
dataArray<Object>noneData that describes lines to be rendered (required)
widthNumber|String1024Chart width
heightNumber|String720Chart height
marginsObject{ top: 50, right: 20, bottom: 50, left: 55 }Chart margins
xLabelString"X"Label for the X axis
yLabelString"Y"Label for the Y axis
hideXLabelBoolfalseStates if the X label is hidden
hideYLabelBoolfalseStates if the Y label is hidden
hideXAxisBoolfalseStates if the X axis is hidden
hideYAxisBoolfalseStates if the Y axis is hidden
xMinStringnoneLower domain for the X axis
xMaxStringnoneHigher domain for the X axis
yMinStringnoneLower domain for the Y axis
yMaxStringnoneHigher domain for the Y axis
isDateBoolfalseDetermines if we need to treat the X dimension as date (or numeric)
xParserFunctionisDate ? d3.time.format("%Y-%m-%d").parse : ((x) => x)Parse X values before scaling
xDisplayFunctionisDate ? d3.time.format("%b %d") : d3.format("d")Parse X values before displaying
ticksNumber10Chart width.
hideLinesBoolfalseStates if lines are drawn
interpolateString"cardinal"Line interpolation function
hidePointsBoolfalseStates if points are shown
pointRadiusNumber5Point radius in pixels
onPointClickFunction(event, point) => console.log(point)Callback for clicking on points
onPointHoverFunctionnoneCallback for hovering on points
onTextClickFunction(text) => console.log(text)Callback for clicking on texts
onTextHoverFunctionnoneCallback for hovering on texts
showLegendsBoolfalseStates if legends are shown
legendPositionString"top-left"Position where the legend is rendered
tooltipClassString"svg-line-chart-tooltip"Tooltip class
pointClassString"svg-line-chart-point"Point class
labelClassString"svg-line-chart-label"Label class

Tooltips

It is easy to hook tooltips onto your chart. Just provide a function on the onPointHover prop that returns a HTML element and this will be displayed inside the tooltip. You can use the class provided by default or write your own and pass to the chart as a tooltipClass prop.

Derived Charts

Turns out a simple Line Chart with the right props can assume a different aspect. For example, setting hideLines={true} gives an awesome Scatter Plot.

import { ScatterPlot } from 'react-linechart'
...
render() {
	return <ScatterPlot id="my-scatter-plot" data={data} />
}

It is also possible to build a "Stair Chart", which is how I am calling a time-table-ish kind of chart when we have start and end dates and want to display them as nice stacked bars. Check the Live Demo to get a better insight.

import { StairChart } from 'react-linechart'
...
render() {
	return <StairChart id="my-stair-chart" data={stairedData} />
}

You can add optional onTextHover and onTextClick functions to interact with the chart.

Parsers

In order to comply with the format specified, you can use 3 utilitaries functions which parse your raw data. They are the following:

parseFlatArray(data, xDimension, yDimensionArray, colorArray, idArray, nameArray)
ParameterTypeDefaultDescription
dataArray<Objects>noneArray of objects describing your data in a flat format
xDimensionsStringnoneProperty that will serve as X dimension
yDimensionArrayArray<Strings>noneArray of properties that will serve as Y dimension
colorArrayArray<Strings>[]Array of hex strings colors that will be assigned in accordance with the yDimensionArray. If no colors are specified, a default array of 20 colors is used
idArrayArray<Strings>[]Array of ids that will be assigned in accordance with yDimensionArray. If no ids are specified, a combination of X and Y dimensions is used
nameArrayArray<Strings>[]Array of names that will be assigned in accordance with yDimensionArray

This is useful when you want to display a multi-line chart in a one-data-per-object basis. Just pick the dimensions you want and the chart will be rendered.

const gsmData = [
	{
		"Year": 1880,
		"Glob": -19,
		"NHem": -33,
		"SHem": -5,		
	},
	{
		"Year": 1881,
		"Glob": -10,
		"NHem": -18,
		"SHem": -2,
	},
	...
];

// Creates a three-line chart: Glob x Year, Glob x NHem, Glob x SHem
const gsmFlat = parseFlatArray(gsmData, "Year", ["Glob", "NHem", "SHem"]);
parseGroupingBy(data, xDimension, yDimension, groupByDimension, nameGenerator, colorArray, idArray)
ParameterTypeDefaultDescription
dataArray<Objects>noneArray of objects describing your data in an indexed format
xDimensionsStringnoneProperty that will serve as X dimension
yDimensionStringnoneProperty that will serve as Y dimension
groupByDimensionStringnoneDimension that will be group lines together
nameGeneratorFunctionnameGenerator : (i) => `Grouped by ${groupByDimension} = ${i}`;Function that will generate a name based on the groupByDimension value
colorArrayArray<Strings>[]Array of hex strings colors that will be assigned in accordance with the yDimensionArray. If no colors are specified, a default array of 20 colors is used
idArrayArray<Strings>[]Array of ids that will be assigned in accordance with yDimensionArray. If no ids are specified, a combination of X and Y dimensions is used

This is useful when you want to aggregate data based on some dimension, an id, for example.

const data = [
	{ id: 1, value: 3, date: "2016-01-01" },
	{ id: 1, value: 4, date: "2016-01-03" },
	{ id: 2, value: 10, date: "2016-01-02" },
	{ id: 1, value: 6, date: "2016-01-04" },
	{ id: 2, value: 13, date: "2016-01-06" },
	{ id: 1, value: 5, date: "2016-01-08" },
	{ id: 2, value: 10, date: "2016-03-20" }
];

const grouped = parseGroupingBy(data, "date", "value", "id");
parseStairChart(data, start, end, name, color)
ParameterTypeDefaultDescription
dataArray<Objects>noneArray of objects describing your data
startStringnoneProperty that will serve as start date
endStringnoneProperty that will serve as end date
nameStringnoneProperty that will serve as name for the given line
colorString"steelblue"Color to fill the line

This is useful when you want to display a kind of time frame.

const stair = [
	{ startDate: "2016-01-01", endDate: "2016-01-04", name: "Task 1" },
	{ startDate: "2016-01-02", endDate: "2016-01-03", name: "Task 2" },
	{ startDate: "2016-01-03", endDate: "2016-01-06", name: "Task 3" },
	{ startDate: "2016-01-05", endDate: "2016-01-10", name: "Task 4" },
	{ startDate: "2016-01-08", endDate: "2016-01-13", name: "Task 5" },
	{ startDate: "2016-01-09", endDate: "2016-01-20", name: "Task 6" }
];
const staired = parseStairChart(stair, "startDate", "endDate", "name");

isDate

The component has a shortcut isDate property which will try to parse your x input as a Date. If you use a numeric value and pass isDate={true}, then unexpected behaviour will happen (same for the reverse). This is supposed to be helpful considering standard scenarios but you can always use the xParser prop to parse whatever data you have to a numeric value and the xDisplay prop to display whatever numeric value you have to something more meaningful to your visualization.

Meanwhile, by default the component will first parse the date in a "YYYY-MM-DD" format in a Date object. By default I'm using d3 functions, but you can write your own or use another Date parser such as MomentJS.

Improvements

This is a work in progress, so expect things to break. You can fork your own version or, better still, contribute for the completeness of this library. Help me making a great tool! :)

1.1.12

8 years ago

1.1.11

8 years ago

1.1.9

9 years ago

1.1.8

9 years ago

1.1.7

9 years ago

1.1.6

9 years ago

1.1.5

9 years ago

1.1.4

9 years ago

1.1.3

9 years ago

1.1.2

9 years ago

1.1.1

9 years ago

1.1.0

9 years ago

1.0.12

9 years ago

1.0.11

9 years ago

1.0.10

9 years ago

1.0.9

9 years ago

1.0.8

9 years ago

1.0.7

9 years ago

1.0.6

9 years ago

1.0.5

9 years ago

1.0.3

9 years ago

1.0.2

9 years ago

1.0.1

9 years ago

1.0.0

9 years ago