Charting in React with ApexCharts

When it comes to the world of research, it is crucial to share your findings with your audience. One of the most common ways to do so is by using charts.

So how do you render your graphs on your website? One method is using images. In some cases, this is perfectly fine. However, there is one tiny issue in this case: sometimes, images don’t render well on high-pixel screens. Moreover, they become blurry when enlarged.

To mitigate this, you would have to increase the graphic’s resolution. But this will lead to another problem: larger images take up more memory and thus take a longer time to load. How do we get rid of this problem?

Luckily, this is where ApexCharts.js comes in. It is an easy-to-use, open source library that allows you to build interactive charts for your project.
Here are some of its features:

  • Responsiveness: Your charts will scale according to the viewing device. This contributes to a better UI for all devices
  • Annotations: Apex also allows you to put labels on your charts, thus helping the reader understand the graphics with ease
    ApexCharts Annotations
  • Animations: Just like annotations, animations bring a better user experience. The best part? You can even customize the look and feel of your animation
    ApexCharts Animations

Getting started with ApexCharts

Before materializing a chart, we first need to initialize a React project:

npx create-react-app apex-tutorial

Next, to install the required dependencies, execute the following terminal command:

npm install apexcharts react-apexcharts

Bar charts

Bar charts are useful when you want to exhibit a comparison of values across various subgroups of your data. One notable example is comparing heights between multiple skyscrapers.

Displaying integers on the x-axis

We will replicate this sample data from Math Goodies:

Math Goodies Data

This piece of code renders a basic bar chart using the data above:

export default function SampleLine() {
  const series = [
    {
      name: "Temperature in Fahrenheit", //will be displayed on the y-axis
      data: [43, 53, 50, 57]
    }
  ];
  const options = {
    chart: {
      id: "simple-bar"
    },
    xaxis: {
      categories: [1, 2, 3, 4] //will be displayed on the x-asis
    }
  };
  return (
    <div>
      <Chart options={options} type="bar" series={series} width="80%" />
    </div>
  );
}

As you can see, the Chart component accepts three important props:

  • The options prop specifies the configuration of the graph. Here, we have specified the labels for the x-axis
  • The type prop tells ApexCharts which kind of chart we want to display. In this case, we are rendering a bar chart
  • The series prop contains the data that we want to display. Apex will display this on the y-axis
    x-axis Integers in ApexCharts

Displaying strings on the x-axis

For this example, we will load this dataset from Statistics How To:

Statistics How To in ApexCharts

We can render this data by writing the following code:

const series = [
  {
    name: "Height in feet",
    data: [2722, 2080, 2063, 1972, 1516],
  },
];
const options = {
  chart: {
    id: "simple-bar",
  },
  xaxis: {
    categories: [
      "Burj Khalifa",
      "Tokyo Sky Tree",
      "KVLY-TV mast",
      "Abraj Al-Bait Towers",
      "Bren Tower",
    ],
  },
};

return (
  <div>
    <Chart options={options} type="bar" series={series} width="80%" />
  </div>
);

Notice that this time, we have passed in an array of string values into the xaxis.categories property. No further configuration was needed!
This will be the output of the program:

x-axis Strings in ApexCharts

Changing the orientation of a chart

By default, Apex displays our charts in vertical orientation. You can render them horizontally by using the option.plotOptions.bar.horizontal property:

const options = {
  plotOptions: {
    bar: {
      horizontal: true, //horizontal bar chart
    },
  },
  //extra code removed for brevity
};

return (
  <div>
    <Chart options={options} type="bar" series={series} width="80%" />
  </div>
);

In the snippet above, we set the horizontal property to true. This will flip the chart’s orientation.

Horizontal Orientation ApexCharts

Pie and donut charts

Pie charts allow you to show data in terms of percentages or ratios.

To demonstrate pie charts, we will use this dataset from Math Is Fun:

Math is Fun Data

Just like bar charts, building pie charts is easy. To do so, you need to pass in your data and assign the type prop to pie like so:

const options = { labels: ["Comedy", "Action", "Romance", "Drama", "SciFi"] };
const series = [4, 5, 6, 1, 5]; //our data

return (
  <div className="donut">
    <Chart options={options} series={series} type="pie" width="380" />
  </div>
);

Here, the options.label property contains an array. Each element in this array corresponds to a section in the chart. Later on, we changed the type prop to pie. This will tell Apex to render a pie chart.

Pie Chart ApexCharts

To morph this into a donut chart, modify the value of type to donut :

<Chart options={options} series={series} type="donut" width="380" />

Donut Chart ApexCharts

Line charts

This type of chart is common when you want to depict trends or behaviors with respect to time.
As an example, we will use this table from Chartio:

Chartio Data

Rendering single values

To get started with line charts, let’s display the Guests column only. In the next section, we will display both Guests and Subscribers in the same graph.
The following code renders information from the Guests array:

const series = [
    {
      name: "Guests",
      data: [19, 22, 20, 26]
    }
  ];
  const options = {
    xaxis: {
      categories: ["2019-05-01", "2019-05-02", "2019-05-03", "2019-05-04"]
    }
  };
  return <Chart type="line" series={series} options={options} />;

In this piece of code, we are rendering the Guests field. Furthermore, we have also used date values on our x-axis. Apex will automatically parse these values and display them as a timeline.

Line Graph ApexCharts

Rendering multiple values

The Apex library also allows users to plot multiple datasets in the same graph.

Here, we will render both the Guests and Subscribers data this time.

To add more data to your sheet, append another object to the series array like so:

const series = [
  {
    name: "Guests",
    data: [19, 22, 20, 26],
  },
  //additional data in this array..
  {
    name: "Subs",
    data: [103, 105, 98, 83],
  },
];

This will be the result:

Line Graph with Multiple Values

Combo charts

In some cases, it is common to display multiple chart types in one figure. One such example can be to couple a bar chart and a line chart together.
To do this with Apex Charts, you can specify the type property in the series array like so:

const series = [
  {
    type: "line", //render a line chart for this data
    name: "Guests",
    data: [19, 22, 20, 26],
  },
  {
    type: "column", //use column chart here.
    name: "Subscribers",
    data: [103, 105, 98, 83],
  },
];
return (
  <div>
    <Chart options={options} type="line" series={series} width="80%" />
  </div>
);

Here, we are rendering the Guests data in a line graph. Later on, we told React to represent the Subscribers dataset with a bar (column) chart.

Combo Charts in ApexCharts

Stroke customization

Apex even offers developers the option to customize the look of their lines.

To opt for a smoother looking line, change the options.stroke.curve property to smooth:

const guestOption = {
  stroke: {
    curve: "smooth",
  },
  //..
};
return (
  <div>
    <Chart type="line" series={guestSeries} options={guestOption} width={500} />
  </div>
);

Line Graph with a Curve in ApexCharts

If you want to use a stepline curve, change the curve option to stepline:

const guestOption = {
  stroke: {
    curve: "stepline",
  },
//further code...

Stepline Graph ApexCharts

Radial charts

Radial charts are suitable for indicating progress. An example is showing the progress of a file download:

const series = [70]; //70 percent
const options = {
  labels: ["Progress"], //label of this diagram
};
return <Chart type="radialBar" series={series} options={options} />;

This time, we set the type property to radialBar. This will display a circular gauge on the page.

Radial Chart ApexCharts

Creating a loader bar

To showcase the capabilities of the radial bar, we will build a simple loading bar using ApexCharts:

const [progress, setProgress] = useState(0);
let interval = useRef(null);

useEffect(() => {
  interval.current = setInterval(() => {
    setProgress((old) => old + 50);
  }, 1000);
  return () => {
    clearInterval(interval.current);
  };
}, []);

useEffect(() => {
  if (progress < 100) return;
  clearInterval(interval.current);
}, [progress]);

const series = [progress]; //70 percent
return <Chart type="radialBar" series={series} options={options} width={500} />;

Here is an explanation of this code:

  • Here, we used an interval Hook. This is an instance of useRef and will be responsible for controlling our interval throughout the application’s lifecycle
  • Furthermore, when the component mounts to the UI, we told React to run a setInterval method. This will increment the value of progress by 50 units
  • Every time the progress Hook changes, the app will check if its value exceeds 100. If this condition is met, React will remove the interval from memory. As a result, the program stops incrementing the value of progress
    ApexCharts Loading Progress

Synchronized Graphs

If you have multiple charts with the same x-axis values, it might be good to visualize them through synced charts.

Criteria

Using synced charts in your app is an effortless process, but you have to ensure that your code meets the following conditions:

  • The xaxis.categories are the same for all graphs
  • The chart.group option should be identical. Otherwise, Apex won’t sync your charts
  • The dimensions (width and height properties) should also be similar
  • options.id should be different for each graph. This allows the library to identify each figure and render them to the screen

Simple usage

The snippet of code below will display the guests and subscribers graphs and sync them together:

//create series and options for our 'guests' data
const guestSeries = [
  {
    name: "Guests",
    data: [19, 22, 20, 26],
  },
];
const guestOption = {
  chart: {
    id: "guest",
    group: "social",
  },
  xaxis: {
    categories: ["2019-05-01", "2019-05-02", "2019-05-03", "2019-05-04"],
  },
};
//create series and options for our 'subscribers' data
const subSeries = [
  {
    name: "Subs",
    data: [103, 105, 98, 83],
  },
];
const subOptions = {
  chart: {
    id: "Subs",
    group: "social", //group name same as guestOptions
  },
  xaxis: {
    categories: ["2019-05-01", "2019-05-02", "2019-05-03", "2019-05-04"],
  },
};
return (
  <div>
    <Chart type="line" series={subSeries} options={subOptions} width={500} />
    <Chart type="line" series={guestSeries} options={guestOption} width={500} />
  </div>
);

In this piece of code, we created a series and an options object for each dataset. It is also important to notice that our group property and the x-axis values of each set are identical. This allows Apex to render the charts and pair them together to build synchronized charts.

This will be the output:

Synchronized Graphs ApexCharts

Animations

As stated earlier, Apex lets developers modify graph animations to suit their needs. In this section, we will cover some important properties that allow control over the animation.

Disabling all animations

To remove animations entirely, assign the options.chart.animations.enabled property to false:

const guestOption = {
  chart: {
    animations: {
      enabled: false, //no animations
    },
  },
  //unnecessary code redacted..
};

return (
  <div>
    <Chart options={guestOption} series={series} type="line" />
  </div>
);

The code above tells React to render the charts and remove the animations.

Disabled Animations in ApexCharts

Changing speed

You can speed up or slow down your animations via the speed property. The default value is 800.
In the code below, we are accelerating our animation:

const options = {
  chart: {
    id: "simple-bar",
    animations: {
      speed: 100, //make the transition faster
    },
//further code..

Speed Up Animation ApexCharts

To make the animation slower, increase the value of speed like so:

const options = {
  chart: {
    id: "simple-bar",
    animations: {
      speed: 1900, //make the transition slower
    },
//further code..

Speed Down Animation ApexCharts

Conclusion

You can find the source code for this program in this CodeSandbox.

In this guide, we discussed a handful of important graphs and concepts to help you get started with the Apex charting library. If you want to render graphs in your web app, then Apex Charts will be a great fit for your arsenal. The lines of code required to render your charts are minimal, thus reducing boilerplate code.

Thank you so much for reading!

The post Charting in React with ApexCharts appeared first on LogRocket Blog.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Charting in React with ApexCharts

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.