CSSとSVGで円グラフを描くには

目次

概要

CSS と SVG のみを使用して円グラフを描く方法について説明します。

表示例

75%

ソース

HTML
<div class="pie-chart-box">
  <svg class="pie-chart" width="150" height="150">
    <circle class="chart-1" cx="50%" cy="50%" r="40"></circle>
    <circle class="chart-2" cx="50%" cy="50%" r="40"></circle>
  </svg>
  <div class="text">75%</div>
</div>
CSS
.pie-chart-box {
  position: relative;
  width: 150px;
  height: 150px;
  .pie-chart {
    border: 1px solid #ddd;
    transform: rotate(-90deg);
    .chart-1 {
      stroke: #ddd;
      stroke-width: 4;
      fill: none;
    }
    .chart-2 {
      stroke: #339;
      stroke-width: 8;
      stroke-dasharray: calc(40 * 2 * pi * 75 / 100) calc(40 * 2 * pi);
      fill: none;
    }
  }
  .text {
    position: absolute;
    top: 0;
    height: 100%;
    width: 100%;
    text-align: center;
    align-content: center;
    font-size: 120%;
    font-weight: bold;
  }
}

説明

ベース円を描く

SVG の <circle> を用いてベースとなる円を描きます。

CSS
.pie-chart-box {
  .pie-chart {
    border: 1px solid #ddd;
    .chart-1 {
      stroke: #ddd;
      stroke-width: 4;
      fill: none;
    }
  }
}
HTML
<div class="pie-chart-box">
  <svg class="pie-chart" width="150" height="150">
    <circle class="chart-1" cx="50%" cy="50%" r="40"></circle>
  </svg>
</div>

数値円を描く

ベース円の上に数値を示す円を描きます。

CSS
.pie-chart-box {
  .pie-chart {
    .chart-1 { ... }
    .chart-2 {
      stroke: #339;
      stroke-width: 8;
      fill: none;
    }
  }
}
HTML
<div class="pie-chart-box">
  <svg class="pie-chart" width="150" height="150">
    <circle class="chart-1" cx="50%" cy="50%" r="40"></circle>
    <circle class="chart-2" cx="50%" cy="50%" r="40"></circle>
  </svg>
</div>

数値円の長さを調整する

storoke-dasharray を用いて数値円を破線にします。第1引数は実線の長さ、第2引数は隙間の長さです。実線の長さを円周(半径40×2×π)の 75% にし、隙間の長さを十分大きな値(円周あれば十分)にすることで、長さ 75% の円弧を描くことができます。

CSS
.pie-chart-box {
  .pie-chart {
    .chart-1 { ... }
    .chart-2 {
      ...
      stroke-dasharray: calc(40 * 2 * pi * 75 / 100) calc(40 * 2 * pi);
    }
  }
}

-90度回転させる

実践の開始点は右端になるので円グラフを -90度 回転させて上端から描画するようにします。

CSS
.pie-chart-box {
  .pie-chart {
    transform: rotate(-90deg);
    .chart-1 { ... }
    .chart-2 { ... }
  }
}

テキストを描画する

テキストを円の中心に配置に表示します。

CSS
.pie-chart-box {
  position: relative;
  width: 150px;
  height: 150px;
  .pie-chart {
    ...
  }
  .text {
    position: absolute;
    top: 0;
    height: 100%;
    width: 100%;
    text-align: center;
    align-content: center;
    font-size: 120%;
    font-weight: bold;
  }
}
HTML
<div class="pie-chart-box">
  <svg class="pie-chart" width="150" height="150">
    <circle class="chart-1" cx="50%" cy="50%" r="40"></circle>
    <circle class="chart-2" cx="50%" cy="50%" r="40"></circle>
  </svg>
  <div class="text">75%</div>
</div>
75%