Расширение:Graph
![]() Статус релиза: стабильно |
|
---|---|
Реализация | Тег , ContentHandler |
Описание | Data-driven graphs |
Автор(ы) |
|
MediaWiki | >= 1.40.0 |
Лицензия | MIT License |
Скачать | |
|
|
Quarterly downloads | 164 (Ranked 62nd) |
Public wikis using | 960 (Ranked 261st) |
Переведите расширение Graph, если оно доступно на translatewiki.net | |
Проблемы | Открытые задачи · Сообщить об ошибке |
Расширение Graph позволяет тегу <graph> строить визуализации данных, такие как гистограммы, круговые диаграммы, временные шкалы и гистограммы (демо) в формате JSON, который отображает график на основе Vega.
Общая информация
Расширение Graph позволяет добавлять яркие графики на основе Vega на вики-страницы. Графики могут быть интерактивными.
Самый простой способ добавить график - использовать готовый шаблон, такой как {{Graph:Chart}}. Эти шаблоны скрывают все сложности Vega. Опытные пользователи могут использовать Graph Sandbox для разработки графиков. Графическая песочница позволяет использовать синтаксис вики-шаблонов в дополнение к JSON. The extension integrates with VisualEditor, providing a simple tool/wizard which generates basic graphs, by entering values directly to the editor.
Полезные ссылки
- Vega 2 documentation - restored Vega 2 documentation pages.
- Guide - General recommendations on how to use graphs in Wiki.
- Interactive Tutorial - step by step instructions how to build a complex interactive graph from scratch
- Demo page - for many samples and usage tricks.
- TechTalk Video - a WMF tech talk discussing the Graph extension, including a great demo of the Lyra editor (also installed on labs).
- You may also be interested in some of the Vega future capabilities (Keynote by Jeffrey Heer).
- Vega for devs - best place of all Vega resources
Установка
- Requires JsonConfig extension
- Скачайте и распакуйте файл(ы) в папку с названием
Graph
в вашей папкеextensions/
. - Добавьте следующий код внизу вашего
LocalSettings.php
:wfLoadExtension( 'Graph' );
- Готово – Перейдите на страницу Special:Version на своей вики, чтобы удостовериться в том, что расширение успешно установлено.
Установка Vagrant:
- Если вы используете Vagrant , установите с помощью
vagrant roles enable graph --provision
Additional config setup
If you are looking to replicate a production environment like en.wiki you will need to complete the following steps:
Roles (only if you decided to use Vagrant)
- Enable graphs role
- Enable scribunto role
- Enable imagemap role
Templates and Lua Modules
- Copy Module:Graph locally
- Copy Module:Graph/doc locally
- Copy Template:Nowrap locally
- Copy Template:Nowrap/styles.css locally
- Copy Module:Chart locally
- Copy Module:Chart/Default_colors locally.
- Copy File:Circle_frame.svg locally
Charts examples
See Demo page for many samples and usage tricks.
User defined fallback
When using client side rendering, it is possible to use Wikimedia Commons to provide a static fallback image to noscript
users.
This is a temporary solution until a new service is put in place to provide server side rendering.
The user must first upload the static graph to Wikimedia Commons.
Fallback images have two variables fallback
and fallbackWidth
.
fallback
relates to a Wikimedia Commons filename.
fallbackWidth
is the fallback images width in pixels.
These variables are pass through the graph in the following way:
<graph fallback="Graph test seddon.png" fallbackWidth=450>
Where lua modules are used such as Module:Graph then these variables can be provided via the tag function. If Template:Graph:Chart were adapted, it would look like this:
{{safesubst:#tag:graph|{{safesubst:#invoke:Graph|chartWrapper}} | fallback = {{{fallback|''}}} | fallbackWidth= {{{fallbackWidth|''}}} }}
It would then be utilised in a template in the following manner:
{{Graph:Chart|width=400|height=100|xAxisTitle=X|yAxisTitle=Y
|type=rect|x=1,2,3,4,5,6,7,8|y=10,12,6,14,2,10,7,9|fallback=Graph test seddon.png|fallbackWidth=450}}
If a fallbackWidth isn't provided but an image is defined then the extension will derive the width from the provided graph width. The reason for this is there is frequently a difference in the rendered image width and the actual image width.
{{Graph:Chart|width=400|height=100|xAxisTitle=X|yAxisTitle=Y
|type=rect|x=1,2,3,4,5,6,7,8|y=10,12,6,14,2,10,7,9|fallback=Graph test seddon.png}}
External data
HTTP(S) protocol cannot be used to get data for the graph.
Instead, use one of the custom wiki protocols like wikiraw:
, wikiapi:
, and others.
Graph extension uses the GraphAllowedDomains
setting to control how these protocols are resolved:
Note that because queries rely on the structure of wikibase items, they may suddenly stop working if the underlying data is edited and changes, as it may yield incomplete, empty or invalid data that can't be used to create a graph. In these cases the graph will end up empty (see phab:T168601).
$wgGraphAllowedDomains = [
# http + https keys lists all of the domains allowed for the external data access.
# Any domain listed here automatically permits all subdomains as well.
# Custom protocols like 'wikiraw' use it to determine which protocol to use.
# This way wikiraw://en.wikipedia.org/Page will be an api request to https://en.wikipedia.org/w/api.php?action=query&titles=Page&...
'https' => [ 'wikipedia.org', 'wikimedia.org', ... ],
'http' => [ 'wmflabs.org', ... ],
# list of domains allowed for the wikirawupload: protocol access.
# Exact match only, no subdomains.
'wikirawupload' => [ 'upload.wikimedia.org' ],
# same as wikirawupload but for Wikidata Sparql queries
'wikidatasparql' => [ 'query.wikidata.org' ],
];
Known bugs & limitations
- phab:tag/graph - Graph extension bugs
- Fails to implement ISO 8601 timescales so only Gregorian calendars can be used in timelines
Internals
When parsing, the Graph extension expands all template parameters/expressions, and stores the complete graph definitions in the ParserOutput, using graph hashes for IDs.
The graph extension adds HTML to the page where graphs should go, a <div>
with a graph-id as the attribute.
Пример:
<div class="mw-graph" data-graph-id="72edc224f0a10b343c1e84f63dbfc97cac9bc957">
</div>
The Graph extension adds an ext.graph
ResourceLoader JavaScript module to the page that includes the Vega library, and puts the JSON of graph definitions into a JavaScript mediawiki.config
variable named wgGraphSpecs
.
Once the client has loaded this module, the Vega JavaScript library populates each <div>
with an HTML canvas and draws the graph in it, replacing the static image.
Security features
<graph>
can be configured to disallow referencing untrusted data sources (e.g. Wikimedia only allows data from the Wikimedia sites).
Лицензия
Vega library is distributed under a modified BSD license acceptable under for us to use.
“ | This appears to be a copy of the BSD license, with some minor (acceptable) modifications. It's not a problem for us to use it, although ideally they would not make changes like this to the license. It's better if people do not make these changes to their license, to avoid confusion (like this) about whether the license is safe for open-source use. | ” |
—Stephen LaPorte |
Настройка
wgGraphAllowedDomains
See the section on external data.
Other variables
- - wgGraphUrlBlacklist has been removed in 787d64a11.
- - wgGraphDataDomains has been removed in e0813f85a. Use wgGraphAllowedDomains instead.
- - wgGraphUserServiceAlways has been removed in b735f63ff4b.
- - wgGraphIsTrusted has been removed in cf80f43e15.
- - $wgGraphImgServiceUrl was deprecated.
Enabling Graph namespace
To store graph definitions as standalone pages in their own namespace, configure Расширение:JsonConfig .
// See https://www.mediawiki.org/wiki/Extension:JsonConfig
$wgJsonConfigModels['graph.jsonconfig'] = 'graph\Content';
$wgJsonConfigs['graph.jsonconfig'] = array(
'namespace' => <PICK-A-NS-NUMBER>,
'nsName' => 'Graph',
'isLocal' => true,
);
VisualEditor module
Since summer 2015, the Graph extension also comes with a module (ext.graph.VisualEditor) which enables graph editing within VisualEditor.
This module was a result of a Google Summer of Code 2015 project. See phab:T89287 for more details.
This module allows users to see graphs within VisualEditor, as opposed to alien extension nodes. Furthermore, users can open up a dialog to edit a graph's type, data and padding. The UI also offers a way to edit a graph's raw JSON specification within VE without having to switch to the classic wikitext editor, in case more advanced users want to tweak settings not supported by the UI.
This first step serves as a stepping stone for many possibilities with graph editing within VisualEditor, and there are a lot of ways in which the module can be improved and expanded.
Это расширение используется в одном или нескольких проектах Викимедиа. Вероятно, это означает, что расширение стабильно и работает достаточно хорошо, чтобы использоваться такими сайтами с высоким трафиком. Найдите название этого расширения в файлах конфигурации Викимедиа CommonSettings.php и InitialiseSettings.php, чтобы узнать, где оно установлено. Полный список расширений, установленных на конкретной вики, можно увидеть на странице Special:Version wiki. |
Troubleshooting broken graphs
Errors with graphs will be logged in the developer console.
Error: Bad constructor arguments (phab:T277906)
To fix: Replace filepath:Earthmap1000x500compac.jpg with filepath:Earthmap1000x500.jpg
TypeError: undefined is not an object (evaluating 'datum.firstYear.value')
To fix: Make sure you have not set default as null
См. также
- Extension:GraphViz — for displaying graphs of sets of vertices connected by edges (i.e. not charts, like this extension)
- Plotly — The open source JavaScript graphing library (with 3d charting capabilities)
- D3 — Data-Driven Documents
Это расширение включено в следующие пакеты и/или вики-фермы: This is not an authoritative list. Some wiki farms/hosts may contain this extension even if they are not listed here. Always check with your wiki farms/hosts or bundle to confirm. |