How to Visualize Data with Pareto Charts Using JavaScript

July 11th, 2023 by Shachee Swadia

Pareto Chart built using JavaScriptWelcome to this step-by-step tutorial that will empower you to create an interactive Pareto chart using JavaScript that will look nice on any device and in any browser!

A Pareto chart is a captivating graphical combo representation that showcases individual values through descending bars, while a line graph illustrates the cumulative total. It is a powerful tool highlighting the relative importance of different categories within a dataset. Named after the visionary economist Vilfredo Pareto, the Pareto chart embodies the Pareto principle, also known as the 80/20 rule. This principle reveals that approximately 80% of effects stem from a mere 20% of causes. With their ability to pinpoint the most significant elements driving a specific scenario, Pareto charts have become indispensable in certain areas of data analysis.

Every chart needs data, and for this tutorial, I have chosen a dataset to serve as an example for illustration. Together, we will embark on a journey to visualize the major customer complaints for consumer loans in a Pareto chart, demonstrating how easily you can achieve it at every step. So get ready, and let’s dive into the world of Pareto charts and create our own interactive masterpiece!

Pareto Chart to Be Created

Take a moment to behold the final Pareto chart that awaits us.

JS Pareto chart preview

Now, let’s dive into the tutorial and follow the steps to learn how to create your own interactive JS Pareto chart without any complaints.

Creating a Pareto Chart

Developing a fully functional Pareto chart is an uncomplicated task that can be completed in four steps. While having an understanding of HTML and JavaScript can be beneficial, it is optional when utilizing a decent JavaScript charting library. The basic steps are as follows:

  • Create an HTML container.
  • Incorporate the required scripts.
  • Input the data you want to visualize.
  • Configure the visualization using JavaScript.

1. Create an HTML container

To house a chart, you’ll need a container. Start by crafting an HTML page that features a block-level element with a unique identifier for easy referencing. To ensure the chart fills the entire page, set the width and height parameters to 100%, or style it based on your preferences.

<html>
  <head>
    <title>Pareto Chart JavaScript</title>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

2. Incorporate the required scripts

In this tutorial, we will be using the AnyChart JS library as an example. However, the fundamental concepts and steps we discuss can also be applied to other charting libraries. AnyChart is a popular choice due to its extensive examples and comprehensive documentation, making it suitable for beginners and experienced professionals.

We will include two essential scripts for the Pareto chart: the core library file, which is a prerequisite for all charts, and the Pareto module.

Remember to add these scripts within the <script> tags in the <head> section of your HTML page. The JS charting code is to be placed within the <script> tags in the <body> section.

<html>
  <head>
    <title>Pareto Chart JavaScript</title>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-pareto.min.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>  
    <div id="container"></div>
    <script>
      // All the code for the JS Pareto Chart will come here
    </script>
  </body>
</html>

3. Input the data you want to visualize

Since the Pareto chart typically involves a small amount of data, it can be directly integrated:

let data = [
  { x: "Managing the loan or lease", value: 15265 },
  { x: "Problems when you are unable to pay", value: 7678 },
  { x: "Taking out the loan or lease", value: 4370 },
  { x: "Shopping for a loan or lease", value: 2029 },
  { x: "Managing the line of credit", value: 806 },
  { x: "Other issues", value: 1427 }
];

4. Configure the visualization using JavaScript

With everything now in place, let me demonstrate how just a few lines of code can quickly generate an interactive Pareto diagram using JavaScript.

To ensure that the enclosed code only runs after the page is fully loaded, encapsulate it within a function like this:

<script>
  anychart.onDocumentLoad(function () {
    // the following code here
  });
</script>

Within the function, first add the data:

anychart.onDocumentLoad(function () {
  let data = [
    { x: "Managing the loan or lease", value: 15265 },
    { x: "Problems when you are unable to pay", value: 7678 },
    { x: "Taking out the loan or lease", value: 4370 },
    { x: "Shopping for a loan or lease", value: 2029 },
    { x: "Managing the line of credit", value: 806 },
    { x: "Other issues", value: 1427 }
  ];
});

Second, create a Pareto chart instance with the provided data:

let chart = anychart.pareto(data);

Third, create two Pareto series, bar (column) and line:

let column = chart.getSeriesAt(0);
let line = chart.getSeriesAt(1);

Fourth, to enhance comprehensibility, add some important captions. For example, name both Y-axes. One (for the Pareto column series) will represent the issue frequency, while the other (for the Pareto line series) will display the cumulative percentage.

chart.yAxis(0).title("Issue frequency");
chart.yAxis(1).title("Cumulative percentage");

Also, it’s always good to properly name the entire chart:

chart.title("Consumer Loan Customer Complaints (CFPB)");

Finally, set the container by referring to the HTML container created in step 1 and initiate the Pareto charting:

chart.container("container");
chart.draw();

And voila! In no time, a visually appealing JavaScript-based Pareto chart displaying consumer grievances is ready! Glance at it and its resulting code below; you can see the interactive version and play with the code here. And keep reading this tutorial for some options to improve this visualization!


<html>
  <head>
    <title>Pareto Chart JavaScript</title>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-pareto.min.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>  
    <div id="container"></div>
    <script>
      anychart.onDocumentReady(function () {
        // add data
        let data = [
          { x: "Managing the loan or lease", value: 15265 },
          { x: "Problems when you are unable to pay", value: 7678 },
          { x: "Taking out the loan or lease", value: 4370 },
          { x: "Shopping for a loan or lease", value: 2029 },
          { x: "Managing the line of credit", value: 806 },
          { x: "Other issues", value: 1427 }
        ];
        // create a pareto chart with the data
        let chart = anychart.pareto(data);
        // set a pareto column series
        let column = chart.getSeriesAt(0);
        // set a pareto line series
        let line = chart.getSeriesAt(1);
        // name the measure axis
        chart.yAxis(0).title("Issue frequency");
        // name the cumulative percentage axis
        chart.yAxis(1).title("Cumulative percentage");
        // add a chart title
        chart.title("Consumer Loan Customer Complaints (CFPB)");
        // set the container element id for the chart
        chart.container("container");
        // initiate the pareto chart drawing
        chart.draw();
      });
    </script>
  </body>
</html>

Customizing a Pareto Chart

Creating a basic Pareto visualization was quite effortless. However, you’ll be pleasantly surprised to discover how you can also easily modify the chart and enhance its aesthetics. Let me show you some ways to customize the Pareto chart and take it to the next level.

1. Modifying the colors

An excellent way to highlight specific points is by assigning different colors to them. To accomplish this, you can modify the colors of the columns based on their values. The example below distinguishes between issues with more than 10% and less than 10% occurrence in customer complaints. This customization will enhance the visual impact of the Pareto chart.

column.fill(function () {
  if (this.rf < 10) {
    return "#b5cfa8";
  }
    return "#57c478";
});
column.stroke(function () {
  if (this.rf < 10) {
    return "#b5cfa8 ";
  }
    return "#57c478";
});

Additionally, to emphasize the cumulative frequency, let’s add a red hue to shade the line. This subtle yet effective customization will make the line stand out and draw attention to the cumulative aspect of the Pareto chart.

line.stroke("#c04d3b");


2. Adding labels to the columns

Furthermore, you can enhance the readability of the Pareto chart by adding labels to the top of each column, allowing the percentage values for quick visibility. This can be achieved by enabling the labels and formatting them to display the corresponding values.

column.labels().enabled(true).format("{%RF}%");


3. Improving the tooltip

In the tooltip, you can provide more details and clarity. For instance, let’s make sure the value, cumulative frequency, and relative frequency are properly displayed once a point is hovered over. This improvement will make the tooltips more informative and useful for the viewers of the Pareto chart.

column.tooltip().format("Value: {%Value}");
line.tooltip().format("Cumulative frequency: {%CF}% \n Relative frequency: {%RF}%");


4. Setting the interval for the right Y-axis

Depending on your data, you may like to adjust the interval between axis ticks to enhance the precision and clarity in the visualization. Let’s modify the interval for the right Y-axis that displays the cumulative frequency.

chart.yAxis(1).scale().ticks().interval(10);


5. Adding the reference lines

You can add line markers to provide additional reference points and aid in data interpretation. Let’s create two dashed horizontal lines at 20% and 80% cumulative frequency values. We’ll offer visual cues that highlight key thresholds by incorporating these reference lines.

// create the first horizontal line marker
chart
  .lineMarker(0)
  .axis(chart.yAxis(1))
  .value(20)
  .stroke("#A5B3B3", 1, "10 2", "round");

// create the second horizontal line marker
chart
  .lineMarker(1)
  .axis(chart.yAxis(1))
  .value(80)
  .stroke("#A5B3B3", 1, "10 2", "round"); 


6. Adding a crosshair

A regular Pareto chart has two series and two Y-axes. Enabling the crosshairs can facilitate identifying and correlating values across both charts. For example, let’s add a horizontal one like this:

chart.crosshair().enabled(true).xLabel(false);


7. Arranging the X-axis labels

To improve the readability of the X-axis labels when they are long, you can change the way they are displayed to avoid overlapping. For instance, let’s arrange them in a staggered manner, in two lines.

chart.xAxis().staggerMode(true);
chart.xAxis().staggerLines(2);


8. Enhancing the title

Customizing the chart title is another aspect you may want to adjust according to your preferences. Here’s what you can do to enhance our Pareto graphic. Firstly, increasing the font size will make it more prominent and eye-catching. Secondly, adding a subtitle can provide additional context and information. Lastly, giving the title a color that matches the columns will create a visually cohesive look, tying all the elements of the Pareto graph together. These enhancements will contribute to a more visually appealing and engaging chart.

chart
  .title()
  .enabled(true)
  .useHtml(true)
  .text(
    '<span style = "color: #111; font-size:20px; margin-bottom:10px; dy:20px">Consumer Loan Customer Complaints (CFPB)</span>' +
    '<br/><span style="color:#57c478; font-size: 15px;">The top 2 issues make up almost 80% of all the issues identified in consumer complaints</span>'
  );

And here’s this tutorial’s final JS Pareto chart; check it out!


Indeed, the graphic now exhibits an elegant and refined appearance with the applied customizations. The combination of color-coded columns, a shaded line, labeled values, improved tooltips, an adjusted Y-axis interval, reference lines, crosshair markers, and an enhanced title contribute to a visually appealing and informative chart.

For the complete code of the finished Pareto chart, you can see it below, and feel free to explore the interactive version of this visualization and further experiment with the code here.

<html>
  <head>
    <title>Pareto Chart JavaScript</title>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-pareto.min.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>  
    <div id="container"></div>
    <script>
      anychart.onDocumentReady(function () {
        // add data
        let data = [
          { x: "Managing the loan or lease", value: 15265 },
          { x: "Problems when you are unable to pay", value: 7678 },
          { x: "Taking out the loan or lease", value: 4370 },
          { x: "Shopping for a loan or lease", value: 2029 },
          { x: "Managing the line of credit", value: 806 },
          { x: "Other issues", value: 1427 }
        ];
        // create a pareto chart with the data
        let chart = anychart.pareto(data);
        // set a pareto column series
        let column = chart.getSeriesAt(0);
        // customize the column colors
        // fill
        column.fill(function () {
          if (this.rf < 10) {
            return "#b5cfa8";
          }
          return "#57c478";
        });
        // stroke
        column.stroke(function () {
          if (this.rf < 10) {
            return "#b5cfa8 ";
          }
          return "#57c478";
        });
        // set a pareto line series
        let line = chart.getSeriesAt(1);
        // customize the line stroke
        line.stroke("#c04d3b");
        // name the measure axis
        chart.yAxis(0).title("Issue frequency");
        // name the cumulative percentage axis
        chart.yAxis(1).title("Cumulative percentage");
        // customize the column label format
        column.labels().enabled(true).format("{%RF}%");
        // customize the tooltip format
        // column series
        column.tooltip().format("Value: {%Value}");
        // line series
        line.tooltip().format("Cumulative frequency: {%CF}% \n Relative frequency: {%RF}%");
        // set the tick interval
        chart.yAxis(1).scale().ticks().interval(10);
        // create the first horizontal line marker
        chart
          .lineMarker(0)
          .axis(chart.yAxis(1))
          .value(20)
          .stroke("#A5B3B3", 1, "10 2", "round");
        // create the second horizontal line marker
        chart
          .lineMarker(1)
          .axis(chart.yAxis(1))
          .value(80)
          .stroke("#A5B3B3", 1, "10 2", "round"); 
        // add a crosshair
        chart.crosshair().enabled(true).xLabel(false);
        // enable the stagger mode for the x-axis labels
        chart.xAxis().staggerMode(true);
        // configure the stagger mode
        chart.xAxis().staggerLines(2);
        // add a chart title
        chart
          .title()
          .enabled(true)
          .useHtml(true)
          .text(
            '<span style = "color: #111; font-size:20px; margin-bottom:10px; dy:20px">Consumer Loan Customer Complaints (CFPB)</span>' +
              '<br/><span style="color:#57c478; font-size: 15px;">The top 2 issues make up almost 80% of all the issues identified in consumer complaints</span>'
          );
        // set the container element id for the chart
        chart.container("container");
        // initiate the pareto chart drawing
        chart.draw();
      });
    </script>
  </body>
</html>

Conclusion

The tutorial shows how to use JavaScript to create and customize an excellent interactive Pareto chart without much hassle. While the exact functions may vary depending on the library, the core methodology remains consistent.

Enjoy creating insightful Pareto charts! If you have any questions or need further assistance, feel free to ask.


Published with the permission of Shachee Swadia. Originally appeared on Hacker Noon with the title “Creating a Pareto Chart With JavaScript” on July 8, 2023.

You may also like to check out the JavaScript Pareto Chart Tutorial originally published on our blog earlier.

See more JavaScript charting tutorials and keep on mastering interactive data visualization.

Got an idea for a cool guest post? Let us know.



No Comments Yet

*