React Visualization Libraries in 2019

React Visualization Libraries in 2019

While working on&nbsp;<a href="https://github.com/statsbotco/cube.js" target="_blank">Cube.js</a>, we’re seeing a lot of different visualization libraries. Given that Cube.js provides an API layer for analytics on top of an SQL database and doesn’t play on the visualization field, any charting library can be used to build dashboards with it. That’s why we’re always on a search for a nice and developer-friendly visualization library.

While working on Cube.js, we’re seeing a lot of different visualization libraries. Given that Cube.js provides an API layer for analytics on top of an SQL database and doesn’t play on the visualization field, any charting library can be used to build dashboards with it. That’s why we’re always on a search for a nice and developer-friendly visualization library.

The list below is for React-specific libraries. I’ll try to build almost the same stacked bar chart with axes formatting, legend and tooltip using every one of it. For the data backend, we’ll use Cube.js hosted on Heroku. I’ll also use Cube.js React binding, which uses the render props technique and doesn’t render anything itself, letting us build whatever we want with any charting library.

Along the way, I’ll also use two very handy libraries—moment.js and numeral.js for dates and numbers formatting, respectively.

As a data input, we are going to use the resultSet.chartPivot() method from the Cube.js Javascript client. It returns an array of data, and in our case, it looks like this:

[
  {
    "x": "2017-01-01T00:00:00.000",
    "completed, Orders.count": 208,
    "processing, Orders.count": 252,
    "shipped, Orders.count": 233
  },
  {
    "x": "2017-02-01T00:00:00.000",
    "completed, Orders.count": 188,
    "processing, Orders.count": 209,
    "shipped, Orders.count": 222
  },
  …
]

Now, let’s jump to the list.

If you don’t see your favorite library or just want me to add one more—just ping me in this Public Slack Community. I’m happy to add as many libraries as I can to the list.

Recharts

Recharts provides a set of modular charting components and does a great job by letting you mix those components together to easily build things like a composed line and bar chart.

It is the most popular library to date. It has more than 11k stars on Github, but a huge number (600 to date) of open issues as well.

The documentation is quite extensive but lacks details in some parts. You can find a bunch of examples at Rechart’s website, which could be a good starting point to building your own charts.

Recharts has a bunch of options for customization. Besides that, it allows low-level customization via custom SVG elements.

Here is how to build our stacked bar chart in Recharts:

In this and all the following examples I'm using colorsdateFormatter, and numberFormatter variables. Here is how they are defined:

const numberFormatter = item => numeral(item).format("0,0");
const dateFormatter = item => moment(item).format("MMM YY");
const colors = ["#7DB3FF", "#49457B", "#FF7C78"];
export default ({ resultSet, colors, dateFormatter, numberFormatter }) => (
  <ResponsiveContainer width="100%" height={300}>
    <BarChart data={resultSet.chartPivot()}>
      <XAxis tickFormatter={dateFormatter} dataKey="x" />
      <YAxis tickFormatter={numberFormatter} />
      {resultSet.seriesNames().map((series, i) => (
        <Bar
          stackId="a"
          dataKey={series}
          name={series.split(",")[0]}
          fill={colors[i]}
        />
      ))}
      <Legend />
      <Tooltip labelFormatter={dateFormatter} formatter={numberFormatter} />
    </BarChart>
  </ResponsiveContainer>
);
Victory

Victory follows the same composable pattern as Recharts. It is developed by Formidable, which has other solid open-source libraries besides Victory as well. It is the only library on the list that also works with React Native.

It’s the second most popular library after Recharts with more than 7K stars on Github, but has 5 times less open issues than Recharts. Victory has a community chat on Spectrum.

It is well documented and has an examples gallery.

Victory comes with two themes: grayscale and material, and allows you to create customer themes to have a consistent look across all the charts.

Below you can see the code for our stacked bar chart with Victory:

const transformResult = (series, resultSet) =>
  resultSet.chartPivot().map(element => ({ x: element.x, y: element[series] }));

export default ({ resultSet, dateFormatter, colors, numberFormatter }) => (
<div height={300}>
<VictoryChart
containerComponent={
<VictoryVoronoiContainer
voronoiDimension="x"
labels={(d, i) => ${resultSet.seriesNames()[i]}: ${d.y}}
labelComponent={
<VictoryTooltip cornerRadius={0} flyoutStyle={{ fill: "white" }} />
}
/>
}
domainPadding={{ x: 20, y: [0, 20] }}
>
<VictoryLegend
colorScale={colors}
data={resultSet.seriesNames().map(series => ({
name: series.split(",")[0]
}))}
orientation="horizontal"
y={275}
x={130}
/>
<VictoryAxis tickFormat={dateFormatter} tickCount={8} />
<VictoryAxis dependentAxis />
<VictoryStack colorScale={colors}>
{resultSet.seriesNames().map((series, i) => (
<VictoryBar key={i} data={transformResult(series, resultSet)} />
))}
</VictoryStack>
</VictoryChart>
</div>
);

Nivo

As well as Recharts and Victory, Nivo is built on top of D3 and is React-specific. But unlike previous libraries it is not composable. It provides one component per chart type and this component is configured via multiple props. Nivo is distributed as a set of packages for specific chart types, for example, @nivo/bar. So, one needs to install a specific package to use a specific chart type.

The project itself is quite active; it has more than 5k stars on Github and almost 300 members in the community chat.

It has interactive documentation, where you can build config for your chart. Although it is nice, It lacks a good old text API reference and search option. It also has a Storybook with examples. It helped me a lot to shortcut the time to build the first chart. Same as Victory, Nivo lets you create your own theme to have a consistent look across all the charts.

We’re going to use the @nivo/bar package for our stack bar chart; you can find a code sample and CodeSandbox demo below.

//https://github.com/plouc/nivo/issues/138#issuecomment-373015114
const ticksFormmater = (ticksCount, value, data, dateFormatter) => {
const valueIndex = data.map(i => i.x).indexOf(value);
if (valueIndex % Math.floor(data.length / ticksCount) === 0) {
return dateFormatter(value);
}

return "";
};

export default ({ resultSet, colors, dateFormatter, numberFormatter }) => (
<div style={{ height: 300 }}>
<ResponsiveBar
enableLabel={false}
colors={colors}
data={resultSet.chartPivot()}
keys={resultSet.seriesNames()}
indexBy="x"
enableGridY={false}
padding={0.3}
margin={{ top: 60, right: 80, bottom: 60, left: 40 }}
axisLeft={{
format: numberFormatter
}}
axisBottom={{
format: value =>
ticksFormmater(8, value, resultSet.chartPivot(), dateFormatter)
}}
tooltip={({ id, value, color }) => (
<strong style={{ color }}>
{id.split(",")[0]}: {numberFormatter(value)}
</strong>
)}
legends={[
{
anchor: "bottom",
direction: "row",
translateY: 50,
itemsSpacing: 2,
itemWidth: 150,
itemHeight: 20,
itemDirection: "left-to-right"
}
]}
/>
</div>
);

BizCharts

BizCharts is React-specific visualization library based on G2, a visualization grammar. It is backed by Alibaba and plays nicely with Ant Design Framework.

It has almost 4k stars on Github, but the majority of development is in Chinese, same for most of the documentation. I think the team is doing a great job of translating the docs, but it is still a work in progress.

Though, it lacks documentation in English the API is pretty straightforward. The only hard thing is to re-format the data into the specific format for the stacked chart.

const stackedChartData = resultSet => {
const data = resultSet
.pivot()
.map(({ xValues, yValuesArray }) =>
yValuesArray.map(([yValues, m]) => ({
x: resultSet.axisValuesString(xValues, ", "),
color: resultSet.axisValuesString(yValues, ", "),
measure: m && Number.parseFloat(m)
}))
)
.reduce((a, b) => a.concat(b));

return data;
};

export default ({ resultSet, dateFormatter, colors, numberFormatter }) => (
<Chart
scale={{ x: { tickCount: 10 } }}
height={400}
data={stackedChartData(resultSet)}
forceFit
>
<Axis name="x" label={{ formatter: dateFormatter }} />
<Axis label={{ formatter: numberFormatter }} name="measure" />
<Tooltip />
<Geom
type="intervalStack"
position={x*measure}
color={["color", colors]}
/>
<Legend itemFormatter={item => item.split(",")[0]} />
</Chart>
)}
/>
);

React-vis

React-vis is being developed by Uber and seems quite active with 5.4k Github stars, 150 open issues, and a lot of recent commits. It is modular, like most of the libraries on the list. It comes with some nice default styles, which should be imported separately as CSS files.

Same as Nivo, it has Storybook with examples. The components API is also well documented. On the customization side you can control the look and feel via custom CSS styles. React-vis also provides a specific component for building custom SVG charts—CustomSVGSeries.

The API is similar to Victory's. You can see I'm using almost the same transformResult from Victory's snippet.

const transformResult = (series, resultSet, dateFormatter) =>
resultSet
.chartPivot()
.map(element => ({ x: Date.parse(element.x), y: element[series] }));

export default ({ resultSet, dateFormatter, colors, numberFormatter }) => (
<XYPlot xType="time" height={300} width={500} stackBy="y">
<XAxis tickFormat={dateFormatter} tickSize={8} />
<YAxis />
{resultSet.seriesNames().map((series, i) => (
<VerticalBarSeries
cluster="stack 1"
key={i}
color={colors[i]}
data={transformResult(series, resultSet, dateFormatter)}
/>
))}
<DiscreteColorLegend
colors={colors}
items={resultSet.seriesNames().map(i => i.split(",")[0])}
orientation="horizontal"
style={{ position: "absolute", left: 130, bottom: -30 }}
/>
</XYPlot>
);

If you don’t see your favorite library or just want me to add one more—just ping me in this Public Slack Community. I’m happy to add as many libraries as I can to the list.

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI


Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.