Chat with us, powered by LiveChat

Creating Calendar Charts with JavaScript

March 4th, 2024 by Nick Gogin

Calendar Charts in JavaScript (HTML5)Building an interactive calendar chart from scratch may initially seem daunting and time-consuming. However, I'm here to show you it's not only manageable but straightforward once you know the steps. Whether you're developing a scheduling application, tracking events, or looking to enhance your web page with a sleek calendar graphic, this tutorial is designed specifically for you. I'll guide you through the steps to create impressive interactive calendar charts using JavaScript, simplifying what may seem complex.

We'll delve into this process using a JavaScript charting library. As a support engineer at AnyChart, and with our JS library recently named best in data visualization, it was a natural choice to use our tool for this tutorial. What about the example data? Other tutorials! There's a treasure trove of JS charting tutorials on our blog, and it occurred to me that compiling these tutorials into a calendar chart would serve as a unique, engaging, and practical example for this guide.

Therefore, the calendar chart created by the end of this tutorial will offer a concise overview of all tutorials published on the AnyChart blog over the last four years, enabling you to quickly discover the ones that interest you the most. All aboard, fellow web developers and data enthusiasts!

Understanding Calendar as Chart

The calendar is commonly recognized as a simple tool for tracking dates — a straightforward system organizing days, weeks, months, and years. It's a familiar fixture in our daily lives, helping us remember appointments and significant events. Essentially, a calendar serves as a chart of time.

Yet, when we shift our perspective to digital applications, the concept of a calendar undergoes a subtle transformation. In data visualization, the calendar chart builds upon the basic functionality of a traditional calendar. This digital version not only fulfills its primary role of representing time but also adds dimensions of interactivity and dynamism.

In a calendar chart, each grid segment corresponds to a specific date, offering an organized framework for displaying various time-based data, such as events or deadlines. It becomes more than just a tool for marking time; it evolves into a dynamic platform for visualizing data in relation to time,

Building Calendar Chart

All the code in this tutorial belongs in a single HTML file. Follow along to create and populate a calendar chart in four stages. After that, we'll delve into styling.

1. HTML Boilerplate and Container

Start by creating an HTML file and inputting the boilerplate code to establish a basic file structure. Within the <body> tag, add a <div> element with a unique ID. This <div> is crucial as it serves as the container for the calendar chart; we'll examine this process more closely as we progress. Meanwhile, let's assign it a descriptive ID of "container."

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Calendar Chart in JavaScript</title>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

Additionally, include a <style> tag in the HTML code to apply some CSS rules for the chart container element.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Calendar Chart in JavaScript</title>
    <style>
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

2. Adding Scripts to HTML

In the <head> section of your HTML file, include the necessary scripts. AnyChart has a modular system, which helps keep projects efficient by allowing you to connect only the chart types and features you need. In our example, we include the Base module, the Calendar module, and the Data Adapter module for loading data from a file.

The JavaScript charting code will be enclosed within <script> tags in the <body> section.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Calendar Chart in JavaScript</title>
    <style>
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-calendar.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-data-adapter.min.js"></script>
  </head>
  <body>
    <div id="container"></div>
    <script>
      <!-- The calendar chart's JS code will be here. -->
    </script>
  <body>
</html>

3. Setting Chart Data

Multiple options exist for loading data. For this calendar chart, I've prepared a JSON file, where each item represents a day on the calendar when a tutorial was published, containing the following properties:

  • X: A string formatted as "YYYY-MM-DD", marking the publication date of a tutorial.
  • Value: An integer indicating the number of tutorials published on that day. Given that no more than one tutorial was published per day in this dataset, the value will always be "1", signifying the days when tutorials were made available.
  • Additional fields: For our purposes, this includes a "Name" string that contains the title of the tutorial, and a "Link" string with the URL.

To incorporate this data into the chart, you can use the Data Adapter module's loadJsonFile() method.

anychart.data.loadJsonFile("https://raw.githubusercontent.com/Bepely/JsonExampleData/main/calendar2023.json",
  (data) => chart.data(data)
);

I'll show you where to add this code block in the following step.

4. Calendar Chart Visualization Setup

With the prerequisites in place, building your first calendar chart is straightforward. The whole following JavaScript code should be placed within the <script> tags in the <body> section of your HTML file.

First, to prevent the code from running before the document is fully loaded, use the onDocumentReady() method:

anychart.onDocumentReady(function () { /* ... */ })

Second, add the data prepared in the previous step:

anychart.onDocumentReady(function () {
  anychart.data.loadJsonFile("https://raw.githubusercontent.com/Bepely/JsonExampleData/main/calendar2023.json",
    (data) => chart.data(data)
  );
});

Third, initialize a calendar chart instance:

const chart = anychart.calendar();

Fourth, specify the HTML container that will host the chart:

chart.container("container");

Fifth, if your calendar chart is expected to extend vertically, dynamically adjust its height for a seamless and responsive display. This adjustment allows for scrolling when needed:

chart.listen("chartDraw", function () {
  document.getElementById("container").style.height =
    chart.getActualHeight() + 5 + "px";
});

Finally, activate the chart drawing process. This step brings your calendar chart to life, visualizing the data within the specified container.

chart.draw();

By following these steps, your web page will now showcase a captivating calendar chart that spans the entire screen. For a hands-on experience, explore its interactive version with the full code (you can also find the code here below). And keep reading, as we'll next explore how to customize such a visualization, unlocking several interesting possibilities.

Basic calendar chart in JavaScript

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-calendar.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-data-adapter.min.js"></script>
    <title>Calendar Chart in JavaScript</title>
    <style>
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      // prevent premature chart script execution
      anychart.onDocumentReady(function () {
        // load data into the chart from a JSON file
        anychart.data.loadJsonFile("https://raw.githubusercontent.com/Bepely/JsonExampleData/main/calendar2023.json",
          // callback function to set chart data
          (data) => chart.data(data)
        );
        // create a calendar chart
        const chart = anychart.calendar();
        // set the container id
        chart.container("container");
        // adjust the chart's height after drawing
        chart.listen("chartDraw", function () {
          document.getElementById("container").style.height =
            chart.getActualHeight() + 5 + "px";
        });
        // draw the chart
        chart.draw();
      });
    </script>
  </body>
</html>

Styling Calendar Chart

With the calendar chart now in place, it's time to personalize and refine it to meet specific aesthetic and functional requirements. This section will guide you through modifying several aspects of the calendar, allowing for a customized visualization experience.

1. Adding Title

A title can be added to enhance the chart's descriptiveness, providing immediate context.

chart.title("JavaScript Charting Tutorials on AnyChart Blog, 2020–2023");

2. Customizing Data Point Color Scale

By default, this kind of calendar chart uses a linear color scale that transitions from light blue (representing the 0 value) to dark blue (representing the maximum value in the dataset). Customization allows for adapting this color scale to better align with the chart's thematic or aesthetic goals. In scenarios where data points represent a uniform value, such as a single tutorial published per day, altering the color scale to a consistent shade, like green, can make the chart visually cohesive.

chart.colorScale().colors(["green"]);

Gradients can be removed by disabling the color range, for a uniform appearance.

chart.colorRange(false);

3. Customizing Months and Years

Adjusting the appearance of calendar elements such as months and years offers further opportunities for customization. Defining the month stroke properties and styling the year titles can significantly affect the chart's overall look and feel, making it more aligned with the desired presentation style.

// customize months
const months = chart.months();
// set stroke for months
months.stroke("black", 1);
// set no data stroke for months
months.noDataStroke("black", 1);

// customize years
const years = chart.years();
// access years' title properties
const yearsTitle = years.title();
// set font color for years' title
yearsTitle.fontColor("darkgray");
// set font size for years' title
yearsTitle.fontSize(23);
// set font weight for years' title
yearsTitle.fontWeight(400);
// set padding for years' title
yearsTitle.padding(0, "25%", 0, 0);

4. Setting Up Tooltips

Dynamic tooltips can be configured to display additional information, such as the name of the tutorial associated with a data point. This feature enhances interactivity, allowing users to gain insights at a glance.

// set tooltip format function
chart.tooltip().format(function () {
  // get pointed article name
  const articleName = this.getData("name");
  // return article name or default text
  return articleName ? articleName : "No Article Name!";
});

These styling options showcase just a few of the ways the calendar chart can be customized to fit different visual and informational needs. Explore the playground demo for a practical look at these customizations in action. The full HTML/CSS/JS code for this enhanced calendar chart visualization is also provided for reference below.

Final calendar chart in JS

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-calendar.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-data-adapter.min.js"></script>
    <title>Calendar Chart in JavaScript</title>
    <style>
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>
      // prevent premature chart script execution
      anychart.onDocumentReady(function () {
        // load data into the chart from a JSON file
        anychart.data.loadJsonFile("https://raw.githubusercontent.com/Bepely/JsonExampleData/main/calendar2023.json",
          // callback function to set chart data
          (data) => chart.data(data)
        );
        // create a calendar chart
        const chart = anychart.calendar();
        // set green color to elements
        chart.colorScale().colors(["green"]);
        // disable color range
        chart.colorRange(false);
        // customize months
        const months = chart.months();
        // set stroke for months
        months.stroke("black", 1);
        // set no data stroke for months
        months.noDataStroke("black", 1);
        // customize years
        const years = chart.years();
        // access years' title properties
        const yearsTitle = years.title();
        // set font color for years' title
        yearsTitle.fontColor("darkgray");
        // set font size for years' title
        yearsTitle.fontSize(23);
        // set font weight for years' title
        yearsTitle.fontWeight(400);
        // set padding for years' title
        yearsTitle.padding(0, "25%", 0, 0);
        // set tooltip format function
        chart.tooltip().format(function () {
          // get pointed article name
          const articleName = this.getData("name");
          // return article name or default text
          return articleName ? articleName : "No Article Name!";
        });
        // set the container id
        chart.container("container");
        // adjust the chart's height after drawing
        chart.listen("chartDraw", function () {
          document.getElementById("container").style.height =
            chart.getActualHeight() + 5 + "px";
        });
        // set the chart title
        chart.title("JavaScript Charting Tutorials on AnyChart Blog, 2020–2023");
        // draw the chart
        chart.draw();
      });
    </script>
  </body>
</html>

Congratulations on reaching this stage! Your commitment has unlocked a bonus feature that leverages the power of event listeners to enrich your calendar chart even further. By integrating the following snippet, each highlighted day — a marker of a tutorial's publication — becomes an interactive gateway:

// handle point click events
chart.listen("pointClick", function (e) {
  // get the link to the article source from the chart data
  const articleLink = chart.data().get(e.dataIndex, "link");
  // check if there's a link
  if (articleLink) {
    // open the link in a new window
    window.open(articleLink, "_blank");
  }
});

This enhancement transforms your calendar, allowing you to not only hover over highlighted days to preview tutorial titles via tooltips but also click to directly access the tutorials themselves. This functionality seamlessly bridges the gap between discovery and learning. Happy exploring!

Conclusion

Creating a calendar chart is a straightforward process that's accessible to enthusiasts and professionals alike, regardless of the skill level. Armed with the insights from this tutorial, you're now equipped to create visually stunning and user-friendly calendar charts, streamlining the representation of time-based data across a myriad of applications.

However, this is merely the beginning of the journey. I encourage you to dive deeper into the world of calendar charting by exploring the calendar chart documentation and drawing inspiration from some cool calendar chart examples.

Happy learning and charting!


Published with the permission of Nick Gogin. Originally appeared on DEV Community with the title “Creating Interactive Calendar Charts in JavaScript” on March 1, 2024.

You’re also welcome to check out the Calendar Chart Tutorial by Shachee Swadia, exclusively published on our blog earlier, visualizing Mike Bostock’s contributions on GitHub, as well as our other JavaScript charting tutorials.

Eager to contribute a cool guest post? Feel free to reach out with your ideas.



No Comments Yet

*