Extension:Graph/ガイド

From mediawiki.org
This page is a translated version of the page Extension:Graph/Guide and the translation is 59% complete.

このページは、Graph 拡張機能を使用する成功事例を記述する、コミュニティ向けページです。../対話的なグラフのチュートリアル も参照してください。

Wikiでグラフを組みたてるには

グラフを記事部分から分離する

記事の一部としてグラフを埋め込むことはできるものの、別個のテンプレートとして保存するほうが実際的です。例えばTemplate:Graph:<yourgraphname>を使用すると以下のコードで埋め込めます

{{Graph:<yourgraphname>}}

グラフをカスタム化できるようにする

グラフの設定を直接、グラフ自体に埋め込めるものの、一般には設計としてよくありません。グラフは柔軟なテンプレートとして作成する必要があり、さまざまなどんなデータセットでも書式でも使えて、複数の記事に再利用できるものが求められます。 たとえばグラフの幅と高さはサンプルのようにハードコードできます:

"width": 400, "height": 200,   // bad design

しかしながら、簡単にカスタマイズできるように、既定値を設定したテンプレートのパラメーターとして作成する必要があります:

{{#tag:graph|{
    ...
    "width": {{{width|400}}}, "height": {{{height|200}}},   // good design
    ...
} }}

データはグラフと分離して保存

上記の書式設定で見たように、データ自体はグラフ内に保存できません。例えば大きな表がありグラフが有効なページの一例として、高額な絵画の一覧(英語版)があり、データを複雑に組み合わせた表を使っています。
{|
! Price 
! Painting 
! Image 
! Artist 
! Year 
! ...
|-
! data-sort-value="$300"|~$300
| ''[[When Will You Marry?|Nafea Faa Ipoipo (When Will You Marry?)]]''
| [[File:Paul Gauguin, Nafea Faa Ipoipo? (When Will You Marry?) 1892, oil on canvas, 101 x 77 cm.jpg|95px]]
| {{sort|Gaugin, Paul|[[Paul Gauguin]]}}
| 1892
...
|}

グラフを作成する簡単な手法としては、まず必要なデータの抽出から始まり、そのデータを表組みの隣にグラフとして配置します。確かにこれでもグラフは作れますが、同じページに同一のデータが2組載る点、値が変わるとどちらも更新が必要な点で、最善の策とはいえません。あるいはまた、グラフが本文に埋め込んである場合、記入したグラフのコードやデータのせいで記事が長くなり - 編集できる人の数を制限してしまいます。その点、グラフを独立したテンプレートとして作成すると、今度は、データ更新のときにそのテンプレートの更新を忘れてしまう恐れがあります。

ここで取上げた適切な解決法とは、時間が経ってもパスの管理がしやすく、当初は使いづらいかもしれませんが、同様のリストに再利用できるものを作ることです。

  1. 生データと別のページを、できるだけJSON形式で設定。そのファイルの構造は、リストに載せるデータに合わせる。
  2. 生データをwikiテーブルに変換するためにLuaモジュールを作成し、整形式の整った形に整形する関数を持たせる。
  3. 同じLuaモジュールを使ってグラフに必要なデータを抽出、別の関数を作成してJSON形式のデータとして出力。
  4. グラフ用テンプレートを作成、上記のデータを取り込んでプロットする
  5. 最後に、以下の2つのスニペットを一覧のページに挿入。

データをきれいに整った「表」に変換するスニペット。

{{#invoke:MyLuaModule|BuildTable|PageWithSourceData|...}}

同じデータを「グラフ」に変換するスニペット。

{{Graph:MyGraph | {{#invoke:MyLuaModule|ExtractGraphData|PageWithSourceData|...}} }}

外部データ

グラフのデータはグラフの定義に埋め込むか、"url"リンクで提供します。標準版のVegaと異なり、グラフのタグはカスタムのウィキ プロトコルのひとつを外部リンクに当てます:

  • tabular:///PageWithTabularDataOnCommons.tab - Gets tabular dataset from Commons. Should be used with "format": {"type": "json", "property": "data"} (or "meta" or "fields"). The data given to the graph is already localized to the wiki language.

For example, this dataset would be given to the graph in this format:

{
  "meta": [{
    "description": "Women's weekly earnings as a percent of men's by age, annual averages",
    "license_code": "CC0-1.0+",
    "license_text": "Creative Commons Zero",
    "license_url": "https://creativecommons.org/publicdomain/zero/1.0/",
    "sources": "Copied from [https://www.bls.gov/opub/ted/2006/oct/wk1/art02.txt bls.gov] (United States Department of Labor)"
  }],

  "fields": [{
    "name": "year",
    "type": "number",
    "title": "Year"
  }, {
    "name": "age_16_24",
    "type": "number",
    "title": "16–24 y/o"
  }, ... ],

  "data": [{
    "year": 1979,
    "age_16_24": 78.5,
      ...
  }, ...]
}
  • map:///PageWithGeoJsonDataOnCommons.map - Gets map dataset from Commons. Should be used with "format": {"type": "json", "property": "data.features"} (can also use "meta" to get the same information as for tabular). The data given to the graph is already localized to the wiki language.
  • wikifile:///Albert_Einstein_photo_1921.jpg - Gets File:Albert_Einstein_photo_1921.jpg image from Commons for an image mark. It is always recommended to add ?width=... (and/or height) to make the image the right size and reduce server load.
  • OBSOLETE, use wikifile: instead wikirawupload:{{filepath:Albert Einstein photo 1921.jpg}} - グラフに使う画像を、例えばコモンズから取得。このタグはアップロードによるコンテンツなら何でも指定できます。* クエリ変数のないドメイン名。ファイルパスを得たり画像をオプションのサイズに設定するには、filepath マジック キーワードを使用。
  • wikiraw:///Article%20title/subpage - ウィキページの生のコンテンツを入手し、パスをそのページのタイトルに設定します。ドメイン名はオプションなのですが、名前を付ける場合はウィキメディアがホストする、たとえばen.wikipedia.org、commons.wikimedia.orgなどの天文のサイトから選んでください。
  • wikiapi:///?action=query&list=allpages - データをMediaWiki APIから転写します。ドメイン名はオプション。
  • wikirest:///api/rest_v1/page/... - RESTbase APIを読み込みます。ドメイン名はオプション。
  • geoshape:///?ids=408,664 or geoshape:///?query=SELECT... - 指定された地域の地形を(topojsonとして)取得するには、Wikidata IDまたはURLエンコードされたクエリ(入手先はSPARQL)を使用して、取得する地形を「id」で特定します。
  • mapsnapshot:///?width=__&height=__&zoom=__&lat=__&lon=__ [&style=__] - 左記のコードで地図のスクリーンショット・サービスにリンクを作り、必要な場所・縮尺・サイズに合わせて静的な地図を描画します。パラメータはそれをスクリーンショット画像に変換するよう、Kartotherianに働きかけます - https://maps.wikimedia.org/img/{style},{zoom},{lat},{lon},{width}x{height}@2x.png

Examples of charts with external data

To see working example of graph json which uses external data it is possible to use Template:Graph:Lines and Template:Graph:Stacked template's debug= parameter. For example below template invocation

{{Graph:Lines
| debug=1
| table=bls.gov/US Women's weekly earnings as a percent of men's by age, annual averages.tab
| type=year | xField=year
| series="age_16_24", "age_25_34", "age_35_44", "age_45_54"
| yZero=false | yMin=50 | yMax=100
}}

will produce following graph consistent json

{
  //
  // ATTENTION: This code is maintained at https://www.mediawiki.org/wiki/Template:Graph:Lines
  //            Please do not modify it anywhere else, as it may get copied and override your changes.
  //            Suggestions can be made at https://www.mediawiki.org/wiki/Template_talk:Graph:Lines
  //
  // Template translation is in https://commons.wikimedia.org/wiki/Data:Original/Template:Graphs.tab
  //

  "version": 5,
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 400,
  "height": 300,
"padding": "strict",
  "signals": [{"name": "rightwidth", "update": "width + padding.right", "value":"400" }],
  "data": [{
    "name": "chart",
    "url": "https://commons.wikimedia.org/w/api.php?action=jsondata&formatversion=2&title=bls.gov%2FUS+Women%27s+weekly+earnings+as+a+percent+of+men%27s+by+age%2C+annual+averages.tab&format=json&origin=*",
    "format": {"type": "json"
      , "property": "data"
      
    },
    "transform": [


      // Convert xField parameter into a field "_xfield"
      {"type": "formula", "as": "_xfield", "expr":
"datetime(datum.year, 0, 1)"
      },
      {"type": "collect", "sort": {"field": ["_xfield"]} }
, {"type": "fold", "fields": ["age_16_24", "age_25_34", "age_35_44", "age_45_54"]}
, {"type": "formula", "as": "_yfield", "expr": "datum.value" }

    ]
  },
// source of labels for `tabletype=tab`
  {
    "name": "labels",
    "url": "https://commons.wikimedia.org/w/api.php?action=jsondata&formatversion=2&title=bls.gov%2FUS+Women%27s+weekly+earnings+as+a+percent+of+men%27s+by+age%2C+annual+averages.tab&format=json&origin=*",
    "format": {"type": "json", "property": "fields"},
    "transform": [


    ]
  },



  ],
  "scales": [
    {
      "name": "x",
      "type": "time",
      "domain": {"data": "chart", "field": "_xfield"},
      "range": "width",
      

      
    },
    {
      "name": "y",
      "type": "linear",
      "range": "height",
      "domain": {"data": "chart", "field": "_yfield"},
      "zero": false,
      "domainMin": 50,
      "domainMax": 100,
      
    },
    {
      "name": "color",
      "type": "ordinal",
      "range": {"scheme": "category10"}, 
      "domain": {"data": "chart", "field": "key"}
    },
{
      "name": "labels",
      "type": "ordinal",
"domain": {"data": "labels", "field": "name"},
      "range": {"data": "labels", "field": "title"},
    }
  ],

  "axes": [
    {
      "scale": "x", "orient": "bottom", "tickSize": 0,
      "tickCount": 7,
      
      
      
      "encode": { 
        "update": { "labels": { 
          
          
        } } 
       }
    },
    {
      "scale": "y", "orient": "left", "tickSize": 0,
      
      
      
      
      "encode": { 
        "labels": { 
          
          
        } 
       }
    }
  ],

  "marks": [
    // Group data by the group parameter or "key", and draw lines, one line per group
    {
      "type": "group",
      "from": {
        "facet": {
          "name": ["key"],
          "data": "chart",
          "groupby": ["key"]
        }
      },
      "marks": [
        {
          "type": "line",
          "from": {"data": ["key"]},
          "encode": {
            "hover": {
              "stroke": {"value": "red"}
            },
            "update": {
              "stroke": {"scale": "color", "field": "key"}
            },
            "enter": {
              "y": {"scale": "y", "field": "_yfield"},
              "x": {"scale": "x", "field": "_xfield"},
              "stroke": {"scale": "color", "field": "key"},
              "interpolate": {"value": "linear"},
              "strokeWidth": {"value": 2.5}
            }
          }
        }
        
      ],
    },





  ]
}
生のグラフデータを参照/編集してください.

よくある問題

注意点:入れ子のテンプレートのパラメータ

テンプレートは原則として、入れ子にするときに半角1文字以上で仕切ります。さもないとグラフは表示すらされず、構文エラーが発生します。ご注意ください。

"values": {{{1|{{#invoke:Graph:Utils|expandDict|{"BR":"pink","US":"blue"} }}}}} // will not render
"values": {{{1|{{#invoke:Graph:Utils|expandDict|{"BR":"pink","US":"blue"} }} }}} // will render, notice the whitespace in the closing braces

グラフに波カッコを使うには

Vega2は"template": "{{indexDate | time: '%b %Y'}}"などテンプレートのパラメータをサポートしますが、MediaWikiはまず「indexDate」テンプレートを検索し、参照読み込みします。これを防ぐには、開く波カッコを\u007bに、閉じる波カッコを\u007dに、またパイプ記号「|」(|)は{{!}}に置換します": : "\u007b{indexDate {{!}} time: '%b %Y'}\u007d"

バグの解消

  • 開発・デバッグに最適な場所は、グラフサンドボックスです。 JSONコードをコピーして、入力した通りにグラフが変化するのをリアルタイムで見ることができます。Graph Sandboxはjsonのコメントを理解し、wikiのマークアップを展開することができます。 変換されたJSONは右下のパネルを参照してください。
  • To get the graph JSON from a template, while the graph is being displayed, use the following oneliner in the browser's debugger console (hit to show the JSON). If there is more than one graph on the page, increment the [0] until you get the one you want. Remove first and last quote, and copy/paste to the Vega editor above.
JSON.stringify(Object.values(mw.config.get("wgGraphSpecs"))[0])
  • In Google Chrome, this will copy the string directly onto the clipboard [1]:
copy(JSON.stringify(Object.values(mw.config.get("wgGraphSpecs"))[0]))
  • また、ブラウザーのデバッガーを使って、興味のあるグラフを(表示されていなくても)検査することができます。<div class="mw-graph ... data-graph-id="834d6921e69e66a00b40d8606e39e414145f8288" ...のようなものが表示されるはずです。 ハッシュ値をコピーし、エスケープを押して(Chromeの場合)、このオンライナーでJSONを表示します(表示されたハッシュ値を自分のものに置き換えます)。 最初と最後の引用を削除して、上のベガエディタにコピー&ペーストしてください。
JSON.stringify(mw.config.get('wgGraphSpecs')['834d6921e69e66a00b40d8606e39e414145f8288'])