dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

flotでのクリックイベント

2012-05-21 16:22:43 | javascript
flotで、グラフの点をクリックしたときにその点の情報を表示させるようなサンプルプログラムです。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>クリックイベント</title>
<script type="text/javascript" src="flot/jquery.js"></script>
<script type="text/javascript" src="flot/jquery.flot.js"></script>
</head>
<body>
クリックイベント<br>
<br>
<div id="graph_area" style="width:600px;height:300px"></div><br>
<br>
<div id="label_area"></div><br>

<script type="text/javascript">
$(function () {
  var data = [
    [0, 3, { label: "a" }],
    [2, 8, { label: "b" }],
    [3, 5, { label: "c" }],
    [1, 4, { label: "d" }],
    [2, 4, { label: "e" }],
  ];


  $.plot($("#graph_area"),
    [
      {
        data: data,
        lines: { show: false },
        points: { show: true },
      },
    ],
    {
      grid: { hoverable: true, clickable: true },
    }
  );


  $("#graph_area").bind("plotclick", function (e, pos, item) {
    if (item) {
      $("#label_area").html("label: [" + data[item.dataIndex][2].label + "]");
    }
  });
});
</script>

</body>
</html>


クリックイベントは、$("#graph_area").bind("plotclick", function (e, pos, item) {...}); で設定します。
グラフの点をクリックされた場合には item に点の値が設定されているので、item の値を使ってイベント処理を行います。

上記のサンプルでは、item.dataIndex でデータの位置を取得し、配列の第3要素のハッシュの情報を取得しています。
plot() の引数の描画データの { data: ... } には普通は [x, y] の配列を指定しますが、上記のサンプルのように 3 要素以上を指定しても動作に問題はないようです。

以下は、[2.0, 8] の点をクリックした直後の画面です。