DEV Community

Yashas Gowda
Yashas Gowda

Posted on

1

Create an Animated Pie Chart in Less Than 20 Lines of Code!

Keep It Super Simple!
When it comes to data visualization, clarity and simplicity are crucial. A well-crafted chart can convey important insights without overwhelming your audience with numbers and decimals. Let's embrace simplicity and create an animation-rich pie chart using CanvasJS, all in less than 20 lines of code.


Pie Chart

Copy and paste the code below into an HTML file and open it in a modern browser. For legacy browsers, please use the code on this page. For a straightforward API explanation, scroll down!

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Animated Pie Chart</title>
    <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
</head>
<body>
    <div id="chartContainer" style="height: 370px; width: 100%;"></div>
    <script>
        window.onload = () => {
            const chart = new CanvasJS.Chart("chartContainer", {
                theme: "light2", // "light1", "light2", "dark1", "dark2"
                animationEnabled: true,
                title: {
                    text: "Desktop Browser Market Share in 2024"
                },
                data: [{
                    type: "pie",
                    indexLabel: "{label}: {y}%",
                    dataPoints: [
                        { y: 67.15, label: "Chrome" },
                        { y: 15.47, label: "Edge" },
                        { y: 7.89, label: "Safari" },
                        { y: 5.81, label: "Firefox" },
                        { y: 2.24, label: "Opera" },
                        { y: 1.44, label: "Others" }
                    ]
                }]
            });
            chart.render();
        };
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Breakdown of the Code

  • <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
    First and foremost, we load the CanvasJS library via CDN.

  • window.onload = () => { ... };
    This line sets up an event handler that runs the enclosed code when the window (webpage) has finished loading. It ensures that all elements are available before the script executes.

  • const chart = new CanvasJS.Chart("chartContainer", { ... });
    Here, we create a new chart instance. The "chartContainer" is the ID of the HTML element where the chart will be rendered.

Chart Configuration Object:

Inside the parentheses, we pass an object that configures the chart. This object includes several properties:

  • theme: "light2": Sets the color theme of the chart. There are options like "light1", "light2", "dark1", and "dark2".

  • animationEnabled: true: Enables animations when the chart is rendered, making it visually engaging.

  • title: { text: "Desktop Browser Market Share in 2024" }: Defines the title of the chart, displayed at the top.

  • data: [{ ... }]: This array contains the data for the chart. Each object inside it represents a dataset. In this case, it’s a pie chart.

Pie Chart Configuration:

Inside the data array, we define:

  • type: "pie": Specifies that we are creating a pie chart.

  • indexLabel: "{label}: {y}%": Displays the label of each segment followed by its percentage, providing a clear representation of the data directly on the chart.

  • dataPoints: [ ... ]: An array of objects that represent the individual segments of the pie chart.

Each object has:

  • y: The percentage value for that segment.

  • label: The name of the segment (e.g., "Chrome").

Rendering the Chart:

  • chart.render();: This line finally draws the chart on the screen using the specified configuration.

Data source: SimilarWeb

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay