mcpField
F
flutter-chart

flutter-chart

github.com/entronad開発1.8k118 回インストール35 週間前に更新
リポジトリ

flutter-chart について

flutter-chartは、Graphicライブラリを使ったFlutterのデータ可視化を支援するスキルです。宣言的なチャート設定に加え、標準チャートや、形状・ツールチップ・注釈のカスタマイズを扱います。

主な機能

  1. 01宣言的なチャートレイヤー設定
  2. 02一般的なチャートの作成
  3. 03形状とツールチップのカスタマイズ
  4. 04インタラクション・選択・アニメーション設定
  5. 05軸と注釈の追加
  6. 06動的データへの対応

活用シーン

  1. 01Flutterアプリで業務データを表示
  2. 02標準チャートにない可視化を構築
  3. 03対話型ツールチップや選択機能の追加
  4. 04データ更新に合わせたチャート表示

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/entronad/graphic --skill flutter-chart

インストール後、Claude Code で/flutter-chartを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
algebra.md
animation.md
annotations.md
chart-widget.md
coordinates.md
customization.md
encodes.md
examples.md
guides.md
marks.md
modifiers.md
scales.md
selections.md
shapes.md
styling.md
transforms.md

詳細

Graphic を使った Flutter チャート

Graphic ライブラリを使用して Flutter でデータ可視化を作成するユーザーを支援するスキルです。Graphic は Grammar of Graphics に基づくチャートライブラリです。

使用する場面

  • ユーザーが Flutter であらゆる種類のチャート(棒、折れ線、面、円、散布図、ヒートマップなど)を作成したい場合
  • ユーザーがチャートの外観、インタラクティブ性、アニメーションの設定についてサポートを必要としている場合
  • ユーザーが Graphic ライブラリの API や使用パターンについて質問した場合
  • ユーザーがデータを視覚的な表現に変換したい場合
  • ユーザーが独自のカスタム可視化を作成したい場合 — Graphic のカスタマイズシステムは最も強力な機能であり、AI 支援開発の大きな強みです

カスタムチャートを使う理由

標準的なチャートタイプ(棒、折れ線、円)で対応できるのは、データ可視化のニーズの一部にすぎません。Graphic は Grammar of Graphics の理論に基づいて構築されているため、すべての視覚レイヤーを個別にカスタマイズできます。

  • カスタムシェイプ — あらゆる形状(三角形、ロリポップ、矢印、ゲージ、ブレットチャート、スパークラインなど)を描画できます
  • カスタムツールチップ — あらゆるレイアウトに対応した、完全にカスタマイズ可能なインタラクティブオーバーレイ
  • カスタムアノテーション — データ位置または絶対位置にあらゆるグラフィックスを描画できます
  • カスタムエンコーダー — 任意のロジックを使ってデータを視覚要素にマッピングできます
  • カスタムモディファイアー — 衝突や配置の動作をカスタム定義できます

このため、AI 支援開発は特に有用です。AI は、手作業では実装が面倒なカスタムシェイプのレンダラー、座標計算、描画コードを作成できます。

ユーザーの要件に標準的なチャートタイプが完全には合わない場合は、カスタマイズを必ず検討してください。 包括的なカスタマイズガイドについては、references/customization.md を参照してください。

クイックスタート

インストール

pubspec.yaml に追加します。

dependencies:
  graphic: ^latest

次に、flutter pub get を実行します。

インポート
import 'package:graphic/graphic.dart';
最小限の例
Chart(
  data: [
    {'category': 'A', 'value': 10},
    {'category': 'B', 'value': 20},
    {'category': 'C', 'value': 15},
  ],
  variables: {
    'category': Variable(
      accessor: (Map map) => map['category'] as String,
    ),
    'value': Variable(
      accessor: (Map map) => map['value'] as num,
    ),
  },
  marks: [IntervalMark()],
  axes: [Defaults.horizontalAxis, Defaults.verticalAxis],
)

基本概念

Graphic は Grammar of Graphics の理論に従っています。チャートは、独立した宣言的なレイヤーで構成されます。

data → Variable → Scale → Encode → Mark → Shape → Render

すべての設定は、単一の Chart<D> ウィジェットコンストラクターを通じて行います。命令型 API はなく、すべての設定は宣言的です。

Chart ウィジェット

Chart<D> は唯一の公開ウィジェットです。型パラメーター D はデータ項目の型です。主なパラメーターは次のとおりです。

パラメーター型用途
dataList<D>必須。 可視化するデータ
variablesMap<String, Variable<D, dynamic>>必須。 データから値を抽出する方法
marksList<Mark>必須。 描画するジオメトリタイプ
coordCoord?座標系(デフォルト:RectCoord)
axesList<AxisGuide>?軸の設定
tooltipTooltipGuide?インタラクション時のツールチップ
crosshairCrosshairGuide?インタラクション時のクロスヘア
annotationsList<Annotation>?静的アノテーション
selectionsMap<String, Selection>?名前付きの選択動作
transformsList<VariableTransform>?データ変換(フィルター、並べ替え、比率)
paddingEdgeInsets Function(Size)?プロット領域の周囲のパディング
transition—Chart ではなく、各 Mark に設定します

すべてのパラメーターの詳細については、references/chart-widget.md を参照してください。

変数

変数は、生データを抽象値にマッピングする方法を定義します。

variables: {
  'date': Variable(
    accessor: (MyData d) => d.date,
    scale: TimeScale(formatter: (t) => DateFormat.MMMd().format(t)),
  ),
  'value': Variable(
    accessor: (MyData d) => d.value,
    scale: LinearScale(min: 0),
  ),
}

各変数には、ドメインから範囲へのマッピングを制御する Scale を設定できます。詳しくは、references/scales.md を参照してください。

マーク

マークは、データを表す幾何学的要素です。

マーク用途デフォルトのシェイプ
IntervalMark棒グラフ、ヒストグラム、円グラフRectShape
LineMark折れ線グラフ、スパークラインBasicLineShape
AreaMark面グラフ、ストリームグラフBasicAreaShape
PointMark散布図、バブルチャートCircleShape
PolygonMarkヒートマップ、ツリーマップHeatmapShape
CustomMarkローソク足、カスタムシェイプ任意の Shape

パラメーターについては references/marks.md を、シェイプのオプションについては references/shapes.md を参照してください。

エンコード(美的マッピング)

エンコードはデータ値を視覚的プロパティにマッピングします。すべてのエンコードは3つのモードをサポートしています:

  1. 固定値: ColorEncode(value: Colors.blue)
  2. 変数マッピング: ColorEncode(variable: 'type', values: Defaults.colors10)
  3. カスタム関数: ColorEncode(encoder: (tuple) => myColorLogic(tuple))

利用可能なエンコード: ColorEncode、SizeEncode、ShapeEncode、LabelEncode、GradientEncode、ElevationEncode。

詳細は references/encodes.md を参照してください。

位置代数(Varset)

位置は Varset 代数を使用して指定し、3つの演算子があります:

演算子名前効果
*Cross変数を異なる次元(x、y)に割り当てます
+Blend同じ次元上で変数を結合します
/Nest変数によってデータをグループ化します
// x=date, y=value, grouped by type
position: Varset('date') * Varset('value') / Varset('type')

詳細は references/algebra.md を参照してください。

座標
  • RectCoord — 直交座標(デフォルト)。transposed、horizontalRange、verticalRange をサポートします。
  • PolarCoord — 円グラフ、レーダーチャート、ローズチャート用の極座標/放射状座標。startAngle、endAngle、startRadius、endRadius をサポートします。

詳細は references/coordinates.md を参照してください。

インタラクション

名前付きセレクションを定義し、エンコードアップデーターで使用します:

selections: {
  'tap': PointSelection(dim: Dim.x),
},
marks: [
  IntervalMark(
    color: ColorEncode(
      value: Colors.blue,
      updaters: {
        'tap': {
          true: (color) => color.withAlpha(255),   // selected
          false: (color) => color.withAlpha(100),  // not selected
        },
      },
    ),
  ),
],

セレクションの種類とジェスチャー設定については references/selections.md を参照してください。

モディファイア

モディファイアはジオメトリの衝突/配置を処理します:

  • StackModifier() — 要素を積み重ねます(積み上げ棒グラフ、積み上げ面グラフ)
  • DodgeModifier() — 並べて配置します(グループ化棒グラフ)
  • JitterModifier() — ランダムに散らします(ストリッププロット)
  • SymmetricModifier() — 対称的に中央揃えします(ストリームグラフ)

references/modifiers.md を参照してください。

アニメーション
IntervalMark(
  transition: Transition(duration: Duration(seconds: 1), curve: Curves.easeOut),
  entrance: {MarkEntrance.y},  // Animate from y=0
  tag: (tuple) => tuple['id'].toString(),  // Element matching for transitions
)

references/animation.md を参照してください。

一般的なチャートレシピ

棒グラフ
marks: [IntervalMark()]
coord: RectCoord()  // default
横向き棒グラフ
marks: [IntervalMark()]
coord: RectCoord(transposed: true)
グループ化棒グラフ
marks: [
  IntervalMark(
    position: Varset('x') * Varset('y') / Varset('group'),
    color: ColorEncode(variable: 'group', values: Defaults.colors10),
    modifiers: [DodgeModifier()],
  ),
]
積み上げ棒グラフ
marks: [
  IntervalMark(
    position: Varset('x') * Varset('y') / Varset('group'),
    color: ColorEncode(variable: 'group', values: Defaults.colors10),
    modifiers: [StackModifier()],
  ),
]
折れ線グラフ
marks: [LineMark()]
スムーズ折れ線グラフ
marks: [
  LineMark(shape: ShapeEncode(value: BasicLineShape(smooth: true))),
]
面グラフ
marks: [AreaMark()]
円グラフ
transforms: [Proportion(variable: 'value', as: 'percent')],
marks: [
  IntervalMark(
    position: Varset('percent') / Varset('category'),
    color: ColorEncode(variable: 'category', values: Defaults.colors10),
    modifiers: [StackModifier()],
  ),
],
coord: PolarCoord(transposed: true, dimCount: 1),
散布図
marks: [
  PointMark(
    size: SizeEncode(variable: 'magnitude', values: [2, 20]),
    color: ColorEncode(variable: 'type', values: Defaults.colors10),
  ),
]
ローズチャート
marks: [IntervalMark(color: ColorEncode(variable: 'name', values: Defaults.colors10))],
coord: PolarCoord(startRadius: 0.15),

より完全な例については references/examples.md を参照してください。

カスタムチャート開発

Graphic の最大の強みは、完全にカスタマイズ可能なレンダリングパイプラインです。標準のチャートタイプが要件を満たさない場合、独自のシェイプ、ツールチップ、アノテーション、エンコーダーを実装することでカスタムビジュアライゼーションを作成できます。

カスタムシェイプ — コア拡張ポイント

Shape 基底クラスを拡張し、drawGroupPrimitives() を実装することで、まったく新しいチャートジオメトリを作成します:

class LollipopShape extends IntervalShape {
  LollipopShape({this.radius = 6});
  final double radius;

  @override
  List<MarkElement> drawGroupPrimitives(
    List<Attributes> group, CoordConv coord, Offset origin,
  ) {
    final rst = <MarkElement>[];
    for (var item in group) {
      if (item.position.any((p) => !p.dy.isFinite)) continue;
      final style = getPaintStyle(item, false, 0, null, null);
      final base = coord.convert(item.position[0]);
      final tip = coord.convert(item.position[1]);

      // Stem line
      rst.add(PolylineElement(
        points: [base, tip],
        style: PaintStyle(strokeColor: style.fillColor, strokeWidth: 2),
        tag: item.tag,
      ));
      // Circle head
      rst.add(CircleElement(
        center: tip, radius: radius, style: style, tag: item.tag,
      ));
    }
    return rst;
  }

  @override
  bool equalTo(Object other) =>
    other is LollipopShape && radius == other.radius;
}

利用可能な基底クラス: IntervalShape、LineShape、AreaShape、PointShape、PolygonShape

利用可能な描画プリミティブ: RectElement、CircleElement、PolygonElement、PolylineElement、ArcElement、SectorElement、SplineElement、PathElement、LabelElement、GroupElement

カスタムツールチップレンダラー
tooltip: TooltipGuide(
  renderer: (Size size, Offset anchor, Map<int, Tuple> selected) {
    final t = selected.values.first;
    return [
      RectElement(
        rect: Rect.fromCenter(center: anchor, width: 100, height: 36),
        borderRadius: BorderRadius.circular(6),
        style: PaintStyle(fillColor: Colors.black87, elevation: 4),
      ),
      LabelElement(
        text: '${t['name']}: ${t['value']}',
        anchor: anchor,
        style: LabelStyle(
          textStyle: TextStyle(color: Colors.white, fontSize: 12),
          align: Alignment.center,
        ),
      ),
    ];
  },
)
カスタムエンコーダー関数

すべてのエンコードは encoder を介して任意のロジックをサポートします:

color: ColorEncode(encoder: (tuple) {
  final v = tuple['value'] as num;
  return v > 100 ? Colors.red : v > 50 ? Colors.orange : Colors.green;
}),

label: LabelEncode(encoder: (tuple) => Label(
  '${tuple['value']}%',
  LabelStyle(textStyle: TextStyle(
    fontSize: (tuple['value'] as num) > 50 ? 14 : 10,
    fontWeight: FontWeight.bold,
  )),
)),
カスタム開発のための主要クラス
クラス目的
Attributesエンコードされたデータ要素 — position、color、gradient、size、label、tag を含みます
CoordConvconvert()/invert() を介して正規化された [0,1] 位置をキャンバスピクセルに変換します
PaintStyle完全なペイント仕様 — 塗りつぶし、ストローク、グラデーション、破線、高度、影
MarkElement描画プリミティブ — カスタムレンダリングの構成要素
getPaintStyle()Attributes から PaintStyle を抽出するユーティリティ

座標処理、すべての描画プリミティブ、カスタムアノテーション、カスタムモディファイア、ベストプラクティスを含む包括的なガイドについては references/customization.md を参照してください。

ガイドと注釈

  • 軸:手早く設定するには Defaults.horizontalAxis、Defaults.verticalAxis を使用するか、AxisGuide でカスタマイズします。references/guides.md を参照してください。
  • ツールチップ:TooltipGuide() を使用します。必要に応じてカスタムレンダラーも指定できます。references/guides.md を参照してください。
  • クロスヘア:CrosshairGuide() を使用します。references/guides.md を参照してください。
  • 注釈:LineAnnotation、RegionAnnotation、TagAnnotation、CustomAnnotation を使用します。references/annotations.md を参照してください。

スタイル設定

  • PaintStyle — 塗りつぶし/ストロークの色、グラデーション、破線パターン、影
  • LabelStyle — テキストのスタイル、配置、回転、オフセット
  • Defaults — 組み込みのカラーパレット(colors10、colors20)、軸のプリセット、デフォルトのスタイル

references/styling.md を参照してください。

イベントストリーム

チャートは、外部イベントとの連携に使用できる StreamController パラメーターを公開しています。

  • gestureStream — ジェスチャーイベントを送受信します
  • resizeStream — サイズ変更イベントに応答します
  • changeDataStream — データ変更イベントに応答します
  • selectionStream(Mark 上)— 選択状態をプログラムから設定します

動的データ

setState() を使って data パラメーターを更新するだけです。

setState(() {
  data = newData;
});

tag が設定されている場合、チャートはトランジションアニメーションとともに自動的に再描画されます。

重要な注意事項

  • Chart ウィジェットは公開されている唯一のウィジェットです。設定はすべてコンストラクターを通じて行います
  • エンコードの color と gradient は相互に排他的です
  • 円グラフには Proportion トランスフォームと PolarCoord(transposed: true, dimCount: 1) が必要です
  • データ状態間の滑らかなトランジションアニメーションには、マークに tag を使用します
  • グループ化(複数系列、積み上げ、ずらし)には Varset の /(ネスト)演算子が必要です
  • 関数型プロパティは、等価性の比較では常に「変更なし」として扱われます

リファレンスファイル

ファイル内容
references/customization.mdカスタムチャート開発ガイド — シェイプ、ツールチップ、注釈、エンコーダー、描画プリミティブ
references/chart-widget.mdChart ウィジェットの全パラメーターのリファレンス
references/marks.mdすべてのマークの種類とパラメーター
references/encodes.md視覚属性のエンコードに関するリファレンス
references/shapes.md各マークのシェイプの種類
references/scales.mdスケールの種類と設定
references/coordinates.md座標系に関するリファレンス
references/guides.md軸、ツールチップ、クロスヘアに関するリファレンス
references/annotations.md注釈の種類に関するリファレンス
references/selections.md選択とインタラクションに関するリファレンス
references/modifiers.mdジオメトリ修飾子に関するリファレンス
references/transforms.mdデータトランスフォームに関するリファレンス
references/algebra.mdVarset 代数に関するリファレンス
references/animation.mdトランジションと開始アニメーションに関するリファレンス
references/styling.mdPaintStyle、LabelStyle、Defaults に関するリファレンス
references/examples.md完全なチャートの例

ユーザーの質問に回答する際は、API の詳細を正確かつ最新の状態で把握するため、ソースコードを読んでください。このライブラリでは、コードコメントがドキュメントとして幅広く活用されています。主なソースディレクトリは次のとおりです。

  • lib/src/chart/ — Chart ウィジェット
  • lib/src/mark/ — マークの種類
  • lib/src/encode/ — エンコードの種類
  • lib/src/shape/ — シェイプの実装
  • lib/src/scale/ — スケールの種類
  • lib/src/coord/ — 座標系
  • lib/src/guide/ — 軸、ツールチップ、クロスヘア、注釈
  • lib/src/interaction/ — 選択、ジェスチャー
  • lib/src/variable/ — 変数とトランスフォーム
  • lib/src/algebra/ — Varset 代数
  • lib/src/common/ — 共通の型(Label、PaintStyle、Defaults)

コメント