模块: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}}