DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How To Create a Network Graph Using JavaScript
  • How To Create a Resource Chart in JavaScript
  • Ultimate Guide to FaceIO
  • How to Make a Chart in JavaScript With Chart.js

Trending

  • Implementing Explainable AI in CRM Using Stream Processing
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Create a Mosaic Chart Using JavaScript

How to Create a Mosaic Chart Using JavaScript

A step-by-step guide for building an interactive JS Mosaic Chart, illustrated by visualizing data on quarterly PC shipments by brand in 2020.

By 
Shachee Swadia user avatar
Shachee Swadia
·
May. 05, 21 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
12.6K Views

Join the DZone community and get the full member experience.

Join For Free

Data visualization is a valuable tool in today’s scenario, with data everywhere and various opportunities to tap into that data to find insights. Visual charts are imperative to communicate ideas, identify patterns, and make the most of the available data.

So then, would you like to quickly and easily learn how to create a really cool chart that showcases data interestingly?

A mosaic chart is a multi-series chart that effectively represents data with over 2 parameters and is so-called because each data point has distinctive indents, making it visually similar to a piece of mosaic art. Not only is this chart beautiful to look at, but is also very helpful in representing multiple variables and recognizing the relationship between these different variables.

The year 2020 was not all bad, at least for the market of personal computers. The sales of PCs increased throughout each quarter of 2020, with more people working and studying from home. I explored how each brand fared in every quarter based on the number of global shipments.

Here is a look at the final chart to get you excited!

Preview of Final Chart

Follow along with this quick tutorial for front-end web developers and data viz enthusiasts to get the hang of creating a Mosaic Chart with JavaScript.

Building a JS Mosaic Chart in 4 Simple Steps

A mosaic chart may look exciting but difficult to create. However, it is pretty straightforward and easy to create this chart with a JavaScript charting library as one can remove a lot of the burden of coding and allow you to get a chart up quickly and with minimal technical details.

For this tutorial, I am using the AnyChart JS library. I’ve chosen AnyChart as it is flexible yet easy to start off. It is especially good for beginners because of the extensive documentation, along with many useful examples.

Having some background with technologies like HTML and JavaScript is an advantage when visualizing data. Nonetheless, it is quite uncomplicated to create interactive charts with a JS library, and the steps for creating mosaic charts with almost any JavaScript library that supports this chart type tend to be more or less the same.

The 4 fundamental steps to creating a JS Mosaic Chart are:

  • Create an HTML page for the chart.
  • Add the necessary JavaScript files.
  • Connect the data.
  • Write the required JS code for drawing the chart.

1. Create a Basic HTML Page

The first thing to do is create a basic HTML page that will hold the chart. Next, create an HTML block element, and to identify this <div> later in the code, I give it an id attribute like 'container.'

HTML
 




x
19


 
1
<!DOCTYPE html>
2
<html>
3
    <head>
4
        <title>JavaScript Mosaic Chart</title>
5
        <style type="text/css">
6
            html,
7
            body,
8
            #container {
9
                width: 100%;
10
                height: 100%;
11
                margin: 0;
12
                padding: 0;
13
            }
14
        </style>
15
    </head>
16
    <body>  
17
        <div id="container"></div>
18
    </body>
19
</html>



I give 100% width and height to the block so that the chart fills the entire page, but it can be specified according to your preference.

2. Reference the necessary JavaScript files

The next step is adding the charting library scripts to create the mosaic chart. I include the corresponding files from AnyChart’s CDN since that is the library I am using. Of course, these scripts can also be downloaded and referenced as such.

For this chart, I need the core script along with the specific module for the mosaic chart. Here, the module for the mosaic chart contains 3 different types of Marimekko charts, mosaic being one of them. If you want to know more about these charts and their specific characteristics, check out the AnyChart documentation about Marimekko charts.

I add both of these scripts to the <head> section of my HTML page.

HTML
 




xxxxxxxxxx
1
26


 
1
<!DOCTYPE html>
2
<html>
3
    <head>
4
        <title>JavaScript Mosaic Chart</title>
5
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js">
6
        </script>
7
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-mekko.min.js">
8
        </script>
9
        <style type="text/css">
10
            html,
11
            body,
12
            #container {
13
                width: 100%;
14
                height: 100%;
15
                margin: 0;
16
                padding: 0;
17
            }
18
        </style>
19
    </head>
20
    <body>  
21
        <div id="container"></div>
22
        <script>
23
            // All the JS code for the mosaic chart will come here.
24
        </script>
25
    </body>
26
</html>



3. Set the Data

I collated the sales data for different PC brands for each quarter of 2020 as given by Gartner. To facilitate the creation of the mosaic chart, I processed the data in a format that is suitable for it, and since the data is limited, I add it directly in the code.

Here, I plot the quarters on the X-axis and the brands as individual tiles, so I add the brands in the header data and the quarterly figures in the rows.

HTML
 




xxxxxxxxxx
1
43


 
1
<!DOCTYPE html>
2
<html>
3
    <head>
4
        <title>JavaScript Mosaic Chart</title>
5
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js">
6
        </script>
7
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-mekko.min.js">
8
        </script>
9
        <style type="text/css">
10
            html,
11
            body,
12
            #container {
13
                width: 100%;
14
                height: 100%;
15
                margin: 0;
16
                padding: 0;
17
            }
18
        </style>
19
    </head>
20
    <body>  
21
        <div id="container"></div>
22
        <script>
23
            var data = {
24
                header: [
25
                    '#',
26
                    'LENOVO',
27
                    'HP',
28
                    'DELL',
29
                    'APPLE',
30
                    'ACER',
31
                    'ASUS',
32
                    'OTHERS'
33
                ],
34
                rows: [
35
                    ['Q1', 12613,11114,10158,3555,2900,2603,8693],
36
                    ['Q2', 16197,16165,10648,4368,4007,3593,9829],
37
                    ['Q3', 18310,15447,10827,5513,5085,4747,11448],
38
                    ['Q4', 21491,15683,13199,6893,4741,4570,12813]
39
                ]
40
            };
41
        </script>
42
    </body>
43
</html>



Now that we have all the prep done, let’s go on to the final step for drawing the chic, interactive JS mosaic chart!

4. Write the JavaScript Code for Your Chart

Writing code might sound daunting for someone with not much coding experience, but believe me, it is literally 5 lines that need to be written to conjure up a beautiful mosaic chart.

Before anything else, I add a function enclosing all the code, which makes sure that the entire code inside it will only execute once the page is ready. I then put the data inside this function.

Next, I create the mosaic chart with the inbuilt function and set the data.

Finally, I add the reference to the container where the chart is to be drawn, set the title of the chart, and initiate the drawing.

HTML
 




xxxxxxxxxx
1
60


 
1
<!DOCTYPE html>
2
<html>
3
    <head>
4
        <title>JavaScript Mosaic Chart</title>
5
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js">
6
        </script>
7
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-mekko.min.js">
8
        </script>
9
        <style type="text/css">
10
            html,
11
            body,
12
            #container {
13
                width: 100%;
14
                height: 100%;
15
                margin: 0;
16
                padding: 0;
17
            }
18
        </style>
19
    </head>
20
    <body>  
21
        <div id="container"></div>
22
        <script>
23
            anychart.onDocumentReady(function () {
24
                var data = {
25
                    header: [
26
                        '#',
27
                        'LENOVO',
28
                        'HP',
29
                        'DELL',
30
                        'APPLE',
31
                        'ACER',
32
                        'ASUS',
33
                        'OTHERS'
34
                    ],
35
                    rows: [
36
                        ['Q1', 12613,11114,10158,3555,2900,2603,8693],
37
                        ['Q2', 16197,16165,10648,4368,4007,3593,9829],
38
                        ['Q3', 18310,15447,10827,5513,5085,4747,11448],
39
                        ['Q4', 21491,15683,13199,6893,4741,4570,12813]
40
                    ]
41
                };
42

          
43
                // create a mosaic chart
44
                var chart = anychart.mosaic();
45

          
46
                // set chart data
47
                chart.data(data);
48

          
49
                // set container id for the chart
50
                chart.container('container');
51

          
52
                // set the chart title  
53
                chart.title("Quarterly Brand-wise Personal Computer Shipments in 2020 (Thousands of Units)");
54

          
55
                // initiate chart drawing
56
                chart.draw();
57
            });
58
        </script>
59
    </body>
60
</html>



Lo-and-behold! A fascinating and functional mosaic chart is created!

Fascinating and Functional Mosaic Chart

You can immediately see how the shipments increase each quarter by the increasing width of every quarter. In brands, Lenovo is the clear market leader and its sales have grown quarter by quarter. Also, something lucidly seen is that Lenovo, HP and Dell capture more than 50% of the market.

Have a look at this initial version of the mosaic chart with the full JS/CSS/HTML code on CodePen.

Customizing the Mosaic Chart

Most of the decent JS charting libraries allow you to customize the charts using their API. These customizations can make your data visualization stand out with personalized aesthetics and improved representation of the message you want to convey.

Now that the basic mosaic chart is created, let me show you how to enhance the chart’s capabilities in representing the data and tweaking its appearance by some simple customizations.

1. Reduce the Space Between Individual Tiles

To improve the appearance of the mosaic, I reduce the space between each of the points with just one line of code.

JavaScript
 




x


 
1
chart.pointsPadding(3);



2. Improve the Data Label Presentation

The values in the data are in the form of figures in thousands. To make it more readable and easily comprehensible, I change the format of the numbers to showcase the figures in millions. I also update the title of the chart to reflect this modification.

JavaScript
 




xxxxxxxxxx
1
11


 
1
// set the chart labels settings
2
chart.labels()
3
    .format(function(e){
4
        var value = ((this.value)/1000).toFixed(2);
5
        return value + " M";
6
    });
7

          
8
...
9

          
10
// set the chart title  
11
chart.title("Quarterly Brand-wise Personal Computer Shipments in 2020");



You can check out the entire code for this intermediate version of the mosaic chart on CodePen.

Intermediate Chart Example

3. Change the Color Theme and Make Other Related Modifications

To make the Mosaic chart more personalized, I decide to use a different color palette. AnyChart offers some great inbuilt themes that include pre-defined settings like the colors for the chart data points as well as background along with distinct fonts. You can also create a custom theme, but for this chart, I choose an out-of-the-box theme that feels like an old-generation PC screen.

I add the theme script in the <head> section and then add a line of code to set the theme for the mosaic chart.

The inherent font size is slightly small for my preference, so I specify the size of the font in the styling. Also, I want the title of the chart to be bigger, so I add some code to modify that as well.

JavaScript
 




xxxxxxxxxx
1
23


 
1
<head>
2
    <script src="https://cdn.anychart.com/releases/8.9.0/themes/dark_blue.min.js">
3
    </script>
4
  
5
...
6
  
7
    <style type="text/css">
8
    #container text {
9
        font-size: 13px;
10
    }
11
    </style>
12
</head>
13

          
14
...
15

          
16
<body>
17
    <script>
18
  
19
    // set the chart theme
20
    anychart.theme('darkBlue');
21
  
22
    </script>
23
</body>



Also, I want the title of the chart to be bigger, so I add some code to modify that as well.

JavaScript
 




xxxxxxxxxx
1


 
1
// set the chart title  
2
chart
3
    .title()
4
    .enabled(true)
5
    .useHtml(true)
6
    .text("<span style = 'font-size:16px';>Quarterly Brand-wise Personal Computer Shipments in 2020</span>");



Aha! Doesn’t the mosaic chart look so very personalized and engaging?

4. Enhance the tooltip

The last thing to do is make the tooltip more informative and better formatted. Since this is a mosaic chart with individual data points very distinctly identifiable, I want the tooltip to show all the data values for that particular quarter. This can be done by specifying the display mode for the tooltip.

Finally, I just tweak the appearance of the tooltip.

JavaScript
 




xxxxxxxxxx
1


 
1
// set union tooltip
2
chart.tooltip().displayMode('union');
3
  
4
// enable HTML in tooltips and format
5
chart
6
    .tooltip()
7
    .useHtml(true)
8
    .format("<h5 style='font-size:14px; margin: 0.5rem 0;'>{%name}</h5>{%SeriesName}: {%value}{scale:(1000)(1000)|( M)}");



That’s it! A very appealing and informative JavaScript Mosaic Chart is ready.

Final Mosaic Chart

Take a look at the final code for the mosaic chart here or on CodePen.

HTML
 




xxxxxxxxxx
1
91


 
1
<!DOCTYPE html>
2
<html>
3
    <head>
4
        <title>JavaScript Mosaic Chart</title>
5
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-core.min.js">
6
        </script>
7
        <script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-mekko.min.js">
8
        </script>
9
        <script src="https://cdn.anychart.com/releases/8.9.0/themes/dark_blue.min.js">
10
        </script>
11
        <style type="text/css">
12
            html,
13
            body,
14
            #container {
15
                width: 100%;
16
                height: 100%;
17
                margin: 0;
18
                padding: 0;
19
            }
20
            #container text {
21
                font-size: 13px;
22
            }
23
        </style>
24
    </head>
25
    <body>  
26
        <div id="container"></div>
27
        <script>
28
            anychart.onDocumentReady(function () {
29
                var data = {
30
                    header: [
31
                        '#',
32
                        'LENOVO',
33
                        'HP',
34
                        'DELL',
35
                        'APPLE',
36
                        'ACER',
37
                        'ASUS',
38
                        'OTHERS'
39
                    ],
40
                    rows: [
41
                        ['Q1', 12613,11114,10158,3555,2900,2603,8693],
42
                        ['Q2', 16197,16165,10648,4368,4007,3593,9829],
43
                        ['Q3', 18310,15447,10827,5513,5085,4747,11448],
44
                        ['Q4', 21491,15683,13199,6893,4741,4570,12813]
45
                    ]
46
                };
47

          
48
                // set the chart theme
49
                anychart.theme('darkBlue');
50

          
51
                // create a mosaic chart
52
                var chart = anychart.mosaic();
53

          
54
                // set points padding
55
                chart.pointsPadding(3);
56

          
57
                // set chart data
58
                chart.data(data);
59

          
60
                // set the chart labels settings
61
                chart.labels()
62
                    .format(function(e){
63
                        var value = ((this.value)/1000).toFixed(2);
64
                        return value + " M";
65
                    });
66

          
67
                // set union tooltip
68
                chart.tooltip().displayMode('union');
69

          
70
                // enable HTML in tooltips and format
71
                chart
72
                    .tooltip()
73
                    .useHtml(true)
74
                    .format("<h5 style='font-size:14px; margin: 0.5rem 0;'>{%name}</h5>{%SeriesName}: {%value}{scale:(1000)(1000)|( M)}");
75

          
76
                // set container id for the chart
77
                chart.container('container');
78

          
79
                // set the chart title  
80
                chart
81
                    .title()
82
                    .enabled(true)
83
                    .useHtml(true)
84
                    .text("<span style = 'font-size:16px';>Quarterly Brand-wise Personal Computer Shipments in 2020</span>");
85

          
86
                // initiate chart drawing
87
                chart.draw();
88
            });
89
        </script>
90
    </body>
91
</html>



Conclusion

As you can see, building a creative and interactive JS Mosaic Chart is not difficult with the help of a charting library. Of course, this is just scratching the surface, so go ahead and experiment with different charts as well as datasets. There are many other JS charting libraries to explore or if you want, check out some awesome other chart types in AnyChart.

Use that Lenovo or Dell (or are you a Mac person?) of yours to create visualizations and please share your creations here. Of course, let me know if you have any questions.

Chart JavaScript library Data visualization HTML

Opinions expressed by DZone contributors are their own.

Related

  • How To Create a Network Graph Using JavaScript
  • How To Create a Resource Chart in JavaScript
  • Ultimate Guide to FaceIO
  • How to Make a Chart in JavaScript With Chart.js

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!