0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Grafanaで2軸複合グラフを作る

Last updated at Posted at 2024-08-02

以下のようなグラフを作ってみました
image.png
元ネタはこんな感じのデータです。
image.png

選択するVisualizationsは、Business Charts
image.png

まずはPostgreSQLでテーブルを作ります。

CREATE TABLE "売上高" (
"年"        decimal(4,0) not null,
"売上高"    decimal(9,0),
"社員数"    decimal(9,0),
PRIMARY KEY("年")
);

INSERT INTO "売上高" VALUES (1993, 202487, 5451);
INSERT INTO "売上高" VALUES (1994, 230507, 5492);
INSERT INTO "売上高" VALUES (1995, 263510, 5660);
INSERT INTO "売上高" VALUES (1996, 319100, 6065);
INSERT INTO "売上高" VALUES (1997, 330028, 6489);
INSERT INTO "売上高" VALUES (1998, 311724, 6621);
INSERT INTO "売上高" VALUES (1999, 307119, 6316);
INSERT INTO "売上高" VALUES (2000, 314246, 6272);
INSERT INTO "売上高" VALUES (2001, 303657, 6251);
INSERT INTO "売上高" VALUES (2002, 298198, 6236);
INSERT INTO "売上高" VALUES (2003, 316578, 6222);
INSERT INTO "売上高" VALUES (2004, 342537, 6294);
INSERT INTO "売上高" VALUES (2005, 380277, 6297);
INSERT INTO "売上高" VALUES (2006, 402886, 6379);
INSERT INTO "売上高" VALUES (2007, 437616, 6585);
...

左のクエリー(Query)は以下の形、テーブル、カラムを指定します。
image.png

年で順番が必要なのでソート(Order by)も指定します。
image.png
件数(Limit)の箇所はデフォルトで50という値が入るんですが、未入力にしておきます。
image.png

VisualEditorのDataset Itemsの箇所には、列名、年、売上高、社員数の順で登録しておきます。Seriesの箇所は何も設定しません。コードで補完します。
image.png

コードの箇所です。2軸あると両側のY軸の目盛がどちらからわからなくなるので色を変えて分かりやすくします。yAxisIndexの指定でグラフの描画(高さ)が変わってくるので必ず指定します。

return {
  dataset: context.editor.dataset,
  series: [
    {
      type: 'bar',
      name: "売上高",
      color: 'blue',
      yAxisIndex: 0,
    },
    {
      type: 'line',
      name: "社員数",
      color:'green',
      yAxisIndex: 1,
    },
  ],
  xAxis: {
    type: 'category',
  },
  yAxis: [
    {
      type: 'value',
      name: '売上高(百万円)',
      min: 0,
      max: 1000000,
      interval: 100000,
      axisLabel: {
        color: 'blue'
      }
    },
    {
      type: 'value',
      name: '社員数(人)',
      min: 0,
      max: 10000,
      interval: 1000,
      axisLabel: {
        color: 'green'
      }
    }
  ]
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?