Data Visualisation in React — Part I: An Introduction to Recharts

Data Science, AI, IoT — we’re creating more data than ever. How can we visualise it for our users?

Jack Rhodes
The Startup
8 min readJan 24, 2020

--

Photo by Carlos Muza on Unsplash

Data science, the Internet of Things and AI are undoubtedly three of the hottest areas in tech in 2019. As an interactive developer, this has meant that my team and I have been working with and visualising a lot of time-series data in our React apps.

In this short series of articles, I walk through how you can use Recharts to display data and how Moment.js can add some enhanced functionality specific to time-series datasets.

In each article, I’ll take you through the different components of our solution, with code snippets so you can build it yourself.

The data we will use is temperature data from here that I’ve cleaned of any unneeded meta-data, converted to JSON, and reformatted to use Unix timestamps. The final array of data looks something like this:

Part I: An introduction to Recharts

In this first article, we look at how Recharts works, setting up a responsive line chart to display our data, adding axes, a tooltip, and finishing by sprinkling in some SVG magic.

If you want to see the finished product you can clone this GitHub repo and run the app for yourself or view it here. The script I used to do this data-prep is also available in the repo. I’ve used create-react-app to initialise the app and we’ll build what we need from there.

If you already feel comfortable with Recharts and want to learn more about how we can use Moment.js to supercharge its ability to handle time-series data. Feel free to skip to part II of this series here (coming soon).

Recharts

Over the past few months, I’ve investigated a couple of different charting libraries in React including react-vis, victory, and vx but the one that stood out for me was Recharts.

Recharts’ website bills it as “Composable, reliable, and powerful” to which I would add that it is quick to get started with and, for the most part, well-documented.

Our first chart

After installing Recharts in our project creating our first chart component is really simple.

To display our temperature data as a line chart we can use the following code.

We start by defining our chart area using a LineChart component, giving it a height and width in pixels for the SVG canvas where Recharts will draw the chart and supplying it with our temperature data.

Next, we add our first chart element; a Line component to display our data. This Line only requires the dataKey prop to tell it what part of our data set to draw. In this case, we want to draw the temperature of each point in time.

Our most basic line chart showing the hourly temperature in London in one week.
Our most basic line chart showing the hourly temperature in London in one week.

This component results in the above chart. That’s how quick Recharts is to get started. But this chart is really limited and has some real problems we need to fix before we can use this to display time-series data usefully and reliably in an application.

  • Our users have no idea what the data is our what scale it is plotted on,
  • The chart’s size is fixed on render and isn’t responsive to different screen-sizes,
  • After its initial render, the chart is static and we can’t interact with it — it may as well be a static image.

Luckily, we can fix all that, so let’s do it.

Improving our basic line chart

XKCD — Convincing https://xkcd.com/833/

Adding x and y axes

Adding our x-axis and y-axis to the charts is also really straight forward. Just like our Line component, Recharts provides XAxis, and YAxis components which can be used with zero configuration.

As you can see in the snippet above, we simply add these axes as child components to our LineChart, and voila… the chart, shown below, magically has axes, but our axes still don’t look quite right. 🤔

Our simple line with basic x and y axes

Correcting the data type

Whilst our y-axis looks correct, our line isn’t looking at the time property of our points when it plots the points relative to the x-axis. Looking at the Recharts docs reveals that the x-axis can take one of two types, category or number, with the default set to category.

An example from Recharts showing categorised data plotted on a line chart.

The category type is intended for data that is divided into buckets like in the example below taken from Recharts’ examples.

This explains the behaviour of our current code. Recharts is plotting a point for each of the data points and evenly spacing them regardless of their ‘time’ attribute, treating each point as its own category.

In the code below we fix this for our chart by telling our x-axis that it has type=number, that its dataKey in our dataset is time and that it should calculate its domain to start at the earliest time in the data set (dataMin) and finish at the latest time in the data set (dataMax).

These properties together mean Recharts plots our data on a continuous linear scale as you would expect with time-series data.

Adding labels to our axes

To give the user some extra context to the data, we can also add labels to our axes using the Label component. To make sure that the labels are rendered within the bounds of the SVG area, we need to add a margin to the LineChart component.

Our chart with properly scaled and labelled axes.

Now our chart is looking better, but we still need to make our chart more responsive, interactive and less boring.

Adding responsiveness and interactivity

At the moment our chart has a fixed height and width and no way to interrogate chart to get more information from the points that interest the user. We want to make our chart more responsive and interactive. Luckily for us, Recharts gives us loads of tools to do this.

The ResponsiveContainer component used in the snippet below can be used to provide an existing chart dynamic height and width props whilst listening for any window resize events. In our temperature chart, we set the width to 100% of the parent element and give it a fixed height of 400 pixels.

The snippet above also adds two new components:

  • CartesianGrid — adds grid lines to the chart that align with the tick marks automatically calculated by the x and y axes,
  • Tooltipadds a tooltip to be drawn onto the chart so the user can be shown more detailed information by hovering over a specific data point.

We have also added two new props to our Line component:

  • dot={false} — removes the markers from each data point to allow the user to see the underlying shape of the data more clearly,
  • type={”natural”} — smooths the line drawn on the chart using d3’s natural curve.
Look, a tooltip!

After these tweaks, our chart is starting to look better, but we know we can make it cooler than this. To make our final aesthetic improvements, let’s harness the power of SVGs.

Harnessing the power of SVG elements

As I mentioned earlier, Recharts is an SVG based charting library and this means that we can use many of the SVG elements we might use elsewhere when creating vector-based graphics. The image below shows the finished product that we’re aiming for in this step.

Adding a gradient to the stroke of the Line component.

Starting to look a bit more interesting, right?

Let’s see how we can add this heatmap gradient to our Line component using Recharts. Firstly, let’s generate a colour map; I based mine on Matplotlib’s plasma colour map and used Coolors to grab some hex values to use in our code.

Next, we need to use these colour values to define a linear gradient in our code. The <defs/> tag is perfect for this. It allows us to define a graphical object that isn’t rendered directly onto the SVG. Instead, we have to tell the SVG where to use it.

In the snippet below, we create a linearGradient inside a defs tag and define our colour scheme. Then we link the stroke prop of our Line to the id of the linearGradient. To make it more visible, we can also thicken up the line using the strokeWidth prop of our Line.

Next steps

So our chart looks pretty good. To recap, so far we’ve:

  • 📉 Visualised some time-series data in the browser using Recharts ,
  • 👀 Added some axes to help our user understand what they’re actually looking at,
  • 💻 Made the chart responsive to improve our user’s experience across different devices,
  • 🛠 Added interactivity through a tooltip that allows the user to interrogate individual points on the chart,
  • 🌈 Harnessed the abilities of SVG elements to render the line as a linear gradient, using colour as another dimension to communicate the data to our user.

This is only scratching the surface on what Recharts can do, and our chart still has room for improvement, especially around the way it handles time values.

In the next article of this series, I’ll dig into how we can use Moment.js to make dates and times in our chart more user-friendly in a really simple way that integrates beautifully with Recharts.

Let me know your thoughts in the comments, it would be great to hear your opinions and experiences on data visualisation in React!

--

--

Jack Rhodes
The Startup

Technology consultant — currently working as a Front-end developer in IBM’s iX London studio. Any views expressed here are my own.