Donut chart using Vue CSS

Data visualization is a crucial aspect of conveying complex information in a clear and engaging manner. Donut charts, with their circular shape and distinctive segments, are effective tools for representing data in an aesthetically pleasing way. In this detailed guide, we’ll explore how to create a donut chart using Vue.js, a progressive JavaScript framework, and CSS.

Understanding Donut Charts:

Donut charts are a variation of pie charts, but with a hole in the center. They are useful for displaying the relationship between parts and the whole, making it easy to compare the contributions of individual segments within a dataset. Vue.js provides an excellent foundation for creating dynamic and interactive donut charts.

Setting Up the Vue.js Project:

Before diving into the implementation, ensure you have Node.js and npm installed on your machine. Start by creating a new Vue.js project using the Vue CLI:

vue create vue-donut-chart
cd vue-donut-chart

Creating the Donut Chart Component:

  1. Create the DonutChart.vue component:
<template>
  <div class="donut-chart">
    <div class="chart-container">
      <div v-for="(segment, index) in segments" :key="index" class="segment" :style="{ '--percentage': segment.percentage + '%' }"></div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      required: true,
    },
  },
  computed: {
    segments() {
      const total = this.data.reduce((acc, segment) => acc + segment.value, 0);
      let startAngle = 0;

      return this.data.map((segment) => {
        const percentage = (segment.value / total) * 100;
        const angle = (percentage * 360) / 100;
        const rotation = startAngle;
        startAngle += angle;

        return {
          percentage,
          rotation,
          color: segment.color,
        };
      });
    },
  },
};
</script>

<style scoped>
.donut-chart {
  width: 300px;
  height: 300px;
  position: relative;
}

.chart-container {
  width: 100%;
  height: 100%;
  position: absolute;
  clip-path: circle(50% at center);
}

.segment {
  width: 100%;
  height: 100%;
  position: absolute;
  clip-path: polygon(0 0, 100% 0, 100% 100%, 50% 50%, 0 100%);
  transform-origin: center center;
}

.segment::before {
  content: '';
  display: block;
  width: 100%;
  height: 100%;
  background-color: transparent;
  border: 10px solid transparent;
  border-radius: 50%;
  transform: translate(-50%, -50%) rotate(var(--percentage));
}
</style>
  1. Use the DonutChart component in App.vue:
<template>
  <div id="app">
    <DonutChart :data="chartData" />
  </div>
</template>

<script>
import DonutChart from './components/DonutChart.vue';

export default {
  components: {
    DonutChart,
  },
  data() {
    return {
      chartData: [
        { value: 30, color: '#3498db' },
        { value: 20, color: '#e74c3c' },
        { value: 50, color: '#2ecc71' },
      ],
    };
  },
};
</script>

<style>
#app {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
</style>

Explanation of the DonutChart Component:

  1. The template section contains a container for the donut chart with dynamically generated segments based on the provided data.
  2. The script section defines the props for receiving data and computes the necessary information for each segment.
  3. The scoped styles apply the necessary CSS for creating the donut chart, utilizing CSS variables for dynamic styling.

Running the Application:

Run the following commands to see your donut chart in action:

npm install
npm run serve

Visit http://localhost:8080 in your browser to view the donut chart populated with the sample data.

Complete implementation of Lightweight Vue component for drawing pure CSS donut charts

Donut chart using Vue CSS
vue-css-donut-chart

Features

◾ No external dependencies.

◾ Vue 2 and Vue 3 support.

◾ Small size footprint.

◾ High test coverage.

◾ Performs automatic font size recalculation as the size of the donut changes.

◾ Supports responsive donut and pie charts.

Installation

Install via yarn or npm

yarn add vue-css-donut-chart

OR

npm install vue-css-donut-chart

Registering vue-css-donut-chart

ES6

import Donut from 'vue-css-donut-chart';
import 'vue-css-donut-chart/dist/vcdonut.css';

Vue.use(Donut);

◾ In-browser using CDNs

Using unpkg
<link rel="stylesheet" href="https://unpkg.com/vue-css-donut-chart@1/dist/vcdonut.css">
<script src="https://unpkg.com/vue-css-donut-chart@1"></script>
<script>
  Vue.use(vcdonut.default);
</script>
Using jsDelivr
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vue-css-donut-chart@1/dist/vcdonut.css">
<script src="https://cdn.jsdelivr.net/npm/vue-css-donut-chart@1/dist/vcdonut.umd.min.js"></script>
<script>
  Vue.use(vcdonut.default);
</script>

Usage

Basic usage

With sane defaults in place, basic usage is as simple as passing a sections array with objects containing a value property. This will create a donut with 2 sections that take up 25% each.

<template>
  <vc-donut :sections="sections">Basic donut</vc-donut>
</template>
<script>
  export default {
    data() {
      return {
        sections: [{ value: 25 }, { value: 25 }]
      };
    }
  };
</script>

Usage with all the available props

<template>
  <vc-donut
    background="white" foreground="grey"
    :size="200" unit="px" :thickness="30"
    has-legend legend-placement="top"
    :sections="sections" :total="100"
    :start-angle="0" :auto-adjust-text-size="true"
    @section-click="handleSectionClick">
    <h1>75%</h1>
  </vc-donut>
</template>
<script>
  export default {
    data() {
      return {
        sections: [
          { label: 'Red section', value: 25, color: 'red' },
          { label: 'Green section', value: 25, color: 'green' },
          { label: 'Blue section', value: 25, color: 'blue' }
        ]
      };
    },
    methods: {
      handleSectionClick(section, event) {
        console.log(`${section.label} clicked.`);
      }
    }
  };
</script>

For brevity, only the section-click event is demonstrated in the above example. You can use all the other section-* events the same way.

Using the component as a pie chart

Making the component look like a pie chart is as simple as setting the thickness to 100.

<template>
  <vc-donut
    :sections="[{ value: 35 }, { value: 15 }, { value: 15 }, { value: 35 }]"
    :thickness="100">
  </vc-donut>
</template>

Note: setting thickness to 100 will completely hide the diagram’s text or slot content. The content will still be present in the DOM, however it won’t be visible for obvious reasons.

API

Props

PropTypeRequiredDefaultDescription
sizeNumberNo250Diameter of the donut. Can be any positive value.
unitStringNo'px'Unit to use for size. Can be any valid CSS unit. Use % to make the donut responsive.
thicknessNumberNo20Percent thickness of the donut ring relative to size. Can be any positive value between 0-100 (inclusive). Set this to 0 to draw a pie chart instead.
textStringNoText to show in the middle of the donut. This can also be provided through the default slot.
backgroundStringNo'#ffffff'Background color of the donut. In most cases, this should be the background color of the parent element.
foregroundStringNo'#eeeeee'Foreground color of the donut. This is the color that is shown for empty region of the donut ring.
start-angleNumberNo0Angle measure in degrees where the first section should start.
totalNumberNo100Total for calculating the percentage for each section.
has-legendBooleanNofalseWhether the donut should have a legend.
legend-placementStringNo'bottom'Where the legend should be placed. Valid values are top, right, bottom and left. Doesn’t have an effect if has-legend is not true.
auto-adjust-text-sizeBooleanNotrueWhether the font-size of the donut content is calculated automatically to fit the available space.
sectionsArrayNo[]An array of objects. Each object in the array represents a section.
section.valueNumberYesValue of the section. The component determines what percent of the donut should be taken by a section based on this value and the total prop. Sum of all the sections’ value should not exceed total, an error is thrown otherwise.
section.colorStringRead descriptionRead descriptionColor of the section. The component comes with 24 predefined colors, so this property is optional if you have <= 24 sections without the color property.
section.labelStringNo'Section <section number>'Name of the section. This is used in the legend as well as the tooltip text of the section.

Events

All the section-* listeners are called with the section object on which the event occurred and the native Event object as arguments respectively. Consider adding a custom property (eg: name) to the section objects to uniquely identify them.

EventParameterDescription
section-clicksection, eventEmitted when a section is clicked.
section-mouseentersection, eventEmitted when the mouseenter event occurs on a section.
section-mouseleavesection, eventEmitted when the mouseleave event occurs on a section.
section-mouseoversection, eventEmitted when the mouseover event occurs on a section.
section-mouseoutsection, eventEmitted when the mouseout event occurs on a section.
section-mousemovesection, eventEmitted when the mousemove event occurs on a section.

Slots

SlotDescription
default slotIf you want more control over the content of the chart, default slot can be used instead of the text prop.
legendSlot for plugging in your own legend.

Leave a Comment