模組:Graph/doc
这是Module:Graph的文档页面
| 此頁面是Module:Graph的模块文档。 此頁面可能包含了模板的使用說明、分類和其他内容。 |
本模組旨在處理一些資料無法與较新的Chart扩展相容的圖表提供基本的圖表顯示功能及簡易資料懸浮框。若需使用圖表原有的互動性功能,建議转换为Chart扩展:如果是{{Graph:Chart}}原有資料結構或圖表性質有在新版圖表支援的範圍內的图表則建議转换为较新的Chart扩展格式。您可以使用Commons上的MediaWiki提供的简单脚本:graphDataImport.js。 |
| 此模块文档已评为alpha版,可接受第三方输入,并可用于少量页面以检查是否存在问题,但需要受到检查。欢迎提供新功能或修改其输入输出机制的建议。 |
本模組為維基百科圖表系統的核心基礎設施。由於 MediaWiki 官方出於安全因素停用了基於 JavaScript/JSON 的 Extension:Graph (Vega) 擴充功能,本模組利用Scribunto的mw.svg程式庫,在純伺服器端重新實作了高效能的圖表與地圖渲染引擎。
模組架構
本系統採用「高內聚、低耦合」的八模組架構設計:
Module:Graph(主路由器與資料變換器)- 負責接收外部調用、解析參數、載入外部資料、過濾髒數據。
- 將扁平化資料 (Long Data) 轉置為渲染器需要的寬表 (Wide Data) 規格(
ChartSpec)。
Module:Graph/SVGRenderer(SVG渲染引擎)- 接收
ChartSpec,並依據資料屬性派發至Module:Graph/ChartRenderer,或現場繪製,也負責SVG節點生成。
- 接收
Module:Graph/ChartRenderer(2D 圖表渲染引擎)- 接收
ChartSpec,主要負責繪製各種類型的圖表再返回Module:Graph/SVGRenderer輸出。
- 接收
Module:Graph/MapRenderer(地圖渲染引擎)- 負責讀取 TopoJSON,執行麥卡托 (Mercator) 等地理投影,並支援亞像素過濾與靜態 SVG 向量字典快取(WorldMapData)。
Module:Graph/RenderUtils(渲染共用工具集)- 提供
Module:Graph/SVGRenderer、Module:Graph/ChartRenderer、Module:Graph/MapRenderer共用函數和工具集。主要負責處理比例尺(Linear/Log/Pow/Sqrt)、座標軸漂亮刻度計算(Nice Ticks)、單調三次樣條插值(Monotone Cubic Spline)。
- 提供
Module:Graph/MathEngine(數學運算引擎與工具集)- 提供與數學運算相關的共用函數和工具集。
Module:Graph/Expression(閹割版JavaScript引擎)- 負責處理來自舊vega中的JavaScript運算式的圖靈不完全(Turing-incomplete)的單行JavaScript運算式解析器。其僅支援JavaScript求值和閉包函數功能,其餘所有流程控制功能皆不提供。本模組的目的僅為了相容舊vega資料處理語法而設計。若用了不提供的JavaScript語法,將自動降級顯示MediaWiki官方的圖表不可用警示。
Module:Graph/Wikidata(維基數據資料讀取)- 專為
<graph>圖表設計之輕量型 Wikidata SPARQL 直譯與資料萃取引擎。
- 專為
五階段外部資料路由管線 (Data Pipeline)
本模組具備強大的外部資料抓取能力。當偵測到 dataUrl 參數或 JSON 中的 url 屬性時,會透過 fetchExternalData 函數進行安全路由:
- 路由 A(網路 API):若開頭為
wikirest://(如 PageViews)或http://,由於 Lua 沙盒限制無法對外連線,將直接觸發 Fallback (優雅降級),交還給 MediaWiki 系統顯示官方停用警語。 - 路由 B(Data: 命名空間):透過
pcall(mw.ext.data.get)拉取維基共享資源的 Tabular Data。 - 路由 C(Module: 命名空間):透過
pcall(mw.loadData)載入靜態 Lua Table,避免重複解析。 - 路由 D(原生 JSON 快取):檢查頁面的
contentModel == "json",若相符則優先呼叫mw.loadJsonData,直接利用 MediaWiki 內建的 JSON 快取通道。 - 路由 E(一般維基代碼):對於包含維基模板語法的 JSON,先呼叫
frame:preprocess()展開模板參數,接著通過內建的 字串狀態機註解剝離器 抹除//與/* */註解,最後才送入mw.text.jsonDecode,確保解析不崩潰。
針對 Lua 5.1 代理表的防呆設計
由於 MediaWiki 的 Scribunto (Lua 5.1) 中,mw.loadData 與 mw.loadJsonData 回傳的是帶有 Metatable 的唯讀代理表(Proxy Table),直接對其使用 # 運算子(如 #features 或 #data)永遠會得到 0。
本系統的資料遍歷全面改用 while table[idx] ~= nil do 迭代,徹底避開此陷阱,確保資料不會因長度運算子失效而全部遺失。
開發者 API 介面
| 方法名稱 | 說明 |
|---|---|
p.chart(frame)
|
標準圖表入口。負責合併 arguments,抓取外部資料並呼叫 SVGRenderer。 |
p.vega(frame)
|
Vega 相容入口。接受單一無名參數傳入的 Vega JSON 字串,模組會自動將其解析並轉譯為內部參數表,無縫輸出 SVG。 |
p.map(frame)
|
地圖入口。將參數轉交給 Module:Graph/MapRenderer 進行處理。
|
p.chartDebuger(frame)
|
偵錯模式。除了輸出 SVG 圖表外,還會在畫面上以文字方式 Dumping 輸出一份完整的 ChartSpec Table 結構,方便開發者驗證資料變換(Data Wrangling)的結果是否正確。
|
舊版說明文檔
| 此模块文档已被保护。此高度可见模块文档具有高風險,或已用于大量頁面或被频繁替换引用。由于破坏或失误影响程度嚴重,因此已被保护,只有錯誤:頁面未被保護。可以編輯。 |
| 相关页面 |
|---|
Module with helper functions for the Graph extension to display graphs and maps. From de:Modul:Graph.
Functions for templates
map
Creates a JSON object for <graph> to display a political map with colored highlights. In the article namespace the template {{Graph:Map}} should be used instead. See its page for use cases.
Maps can be found at Special:Prefixindex/Template:Graph:Map/Inner/ (for example Template:Graph:Map/Inner/Worldmap2c-json with country borders) and new maps should also be saved under Module:Graph/.
Parameters:
- basemap: sets the base map. The map definitions must follow the TopoJSON format and if saved in Wikipedia are available for this module. Maps in the default directory Special:Prefixindex/Template:Graph:Map/Inner/ like Template:Graph:Map/Inner/Worldmap2c-json should only be referenced by their name while omitting the Module:Graph/ prefix to allow better portability. The parameter also accepts URLs, e.g. maps from other Wikipedia versions (the link should follow the scheme of
//en.wikipedia.org/w/index.php?title=mapname&action=raw, i.e. protocol-relative without leading http/s and a trailing action=raw to fetch the raw content only). URLs to maps on external sites should be avoided for the sake of link stability, performance, security, and she be assumed to be blocked by the software or browser anyway. - scale: the scaling factor of the map (default: 100)
- projection: the map projection to use. Supported values are listed at https://github.com/d3/d3-geo-projection. The default value is
equirectangularfor an equirectangular projection. - center: map center (corresponds in the map data to both comma-separated values of the
scalefield) - feature: which geographic objects should be displayed (corresponds in the map data to the name of the field under the
objectsfield). The default is valuecountries. - ids of geographic entities: The actual parameter names depend on the base map and the selected feature. For example, for the above mentioned world map the ids are ISO country codes. The values can be either colors or numbers in case the geographic entities should be associated with numeric data:
DE=lightbluemarks Germany in light blue color, andDE=80.6assigns Germany the value 80.6 (population in millions). In the latter case, the actual color depends on the following parameters. - colorScale: the color palette to use for the color scale. The palette must be provided as a comma-separated list of color values. The color values must be given either as
#rgb/#rrggbbor by a CSS color name. Instead of a list, the built-in color palettescategory10andcategory20can also be used. - scaleType: supported values are
linearfor a linear mapping between the data values and the color scale,logfor a log mapping,powfor a power mapping (the exponent can be provided aspow 0.5),sqrtfor a square-root mapping, andquantizefor a quantized scale, i.e. the data is grouped in as many classes as the color palette has colors. - domainMin: lower boundary of the data values, i.e. smaller data values are mapped to the lower boundary
- domainMax: upper boundary of the data values, i.e. larger data values are mapped to the upper boundary
- legend: show color legend (does not work with
quantize) - defaultValue: default value for unused geographic entities. In case the id values are colors the default value is
silver, in case of numbers it is 0. - formatjson: format JSON object for better legibility
chart
Creates a JSON object for <graph> to display charts. In the article namespace the template Template:Graph:Chart should be used instead. See its page for use cases.
Parameters:
- width: width of the chart
- height: height of the chart
- type: type of the chart:
linefor line charts,areafor area charts, andrectfor (column) bar charts, andpiefor pie charts. Multiple series can stacked using thestackedprefix, e.g.stackedarea. - interpolate: interpolation method for line and area charts. It is recommended to use
monotonefor a monotone cubic interpolation – further supported values are listed at https://github.com/nyurik/vega/wiki/Marks#line. - colors: color palette of the chart as a comma-separated list of colors. The color values must be given either as
#rgb/#rrggbb/#aarrggbbor by a CSS color name. For#aarrggbbtheaacomponent denotes the alpha channel, i.e. FF=100% opacity, 80=50% opacity/transparency, etc. (The default color palette if n <= 10 is Category10: Template:ChartColors else is Category20: Template:ChartColors). See Template:ChartColors for details. - xAxisTitle and yAxisTitle: captions of the x and y axes
- xAxisMin, xAxisMax, yAxisMin, and yAxisMax: minimum and maximum values of the x and y axes (not yet supported for bar charts). These parameters can be used to invert the scale of a numeric axis by setting the lowest value to the Max and highest value to the Min.
- xAxisFormat and yAxisFormat: changes the formatting of the axis labels. Supported values are listed at https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#numbers for numbers. For example, the format
%can be used to output percentages. For date/time specification of supported values is https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md , e.g.xAxisFormat=%d-%m-%Yfor result 13-01-1977. - xAxisAngle: rotates the x axis labels by the specified angle. Recommended values are: -45, +45, -90, +90
- xType and yType: data types of the values, e.g.
integerfor integers,numberfor real numbers,datefor dates (e.g. YYYY-MM-DD), andstringfor ordinal values (usestringto prevent axis values from being repeated when there are only a few values). Remarks:Datetype doesn't work for bar graphs. Fordatedata input please use ISO date format (e.g. YYYY-MM-DD) acc. to date and time formats used in HTML. Other date formats may work but not in all browsers. Date is unfortunately displayed only in en-US format for all Wikipedia languages. Workaround is to use xAxisFormat and yAxisFormat with numerical dates format. - xScaleType and yScaleType: scale types of the x and y axes, e.g.
linearfor linear scale (default),logfor logarithmic scale andsqrtfor square root scale.- A logarithmic chart allows only positive values to be plotted. A square root scale chart cannot show negative values.
- x: the x-values as a comma-separated list, for dates and time see remark in xType and yType
- y or y1, y2, …: the y-values for one or several data series, respectively. For pie charts
y2denotes the radius of the corresponding sectors. For dates and time see remark in xType and yType - legend: show legend (only works in case of multiple data series)
- y1Title, y2Title, …: defines the label of the respective data series in the legend
- linewidth: line width for line charts or distance between the pie segments for pie charts. Setting to 0 with
type=linecreates a scatter plot. - linewidths: different line widths may be defined for each series of data with csv, if set to 0 with "showSymbols" results with points graph, eg.:
linewidths=1, 0, 5, 0.2 - showSymbols: show symbol on data point for line graphs, if a number is provided, the symbol size (default 2.5) may be defined for each data series, eg.:
showSymbols=1, 2, 3, 4 - symbolsShape: custom shape for symbol: circle, x, square, cross, diamond, triangle_up, triangle_down, triangle_right, triangle_left. May be defined for each series of data with csv, eg.:
symbolsShape= circle, cross, square - symbolsNoFill: if true symbol will be without fill (only stroke),
- symbolsStroke: if "x" symbol is used or option "symbolsNoFill" symbol stroke width, default 2.5
- showValues: Additionally, output the y values as text. (Currently, only (non-stacked) bar and pie charts are supported.) The output can be configured used the following parameters provided as
name1:value1, name2:value2(e.g.|showValues=fontcolor:blue,angle:0).- format: Format the output according to https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#numbers for numbers and https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md for date/time.
- fontcolor: text color
- fontsize: text size
- offset: move text by the given offset. For bar charts and pie charts with
midanglethis also defines if the text is inside or outside the chart. - angle (pie charts only): text angle in degrees or
midangle(default) for dynamic angles based on the mid-angle of the pie sector.
- innerRadius: For pie charts: defines the inner radius to create a doughnut chart.
- xGrid and yGrid: display grid lines on the x and y axes.
- Annotations
- vAnnotationsLine and hAnnotationsLine: display vertical or horizontal annotation lines on specific values e.g.
hAnnotationsLine=4, 5, 6 - vAnnotationsLabel and hAnnotationsLabel: display vertical or horizontal annotation labels for lines e.g.
hAnnotationLabel = label1, label2, label3
- vAnnotationsLine and hAnnotationsLine: display vertical or horizontal annotation lines on specific values e.g.
- formatjson: format JSON object for better legibility
Template wrappers
The functions mapWrapper and chartWrapper are wrappers to pass all parameters of the calling template to the respective map and chart functions.
Note: In the editor preview the graph extension creates a Canvas (HTML元素) with vector graphics. However, when saving the page a PNG raster graphics is generated instead. {{#invoke:Graph|function_wrapper_name}}