From mediawiki.org
Jump to navigation Jump to search
This page is a translated version of the page Extension:Graph and the translation is 37% complete.
Other languages:
English • ‎Türkçe • ‎español • ‎français • ‎occitan • ‎русский • ‎中文 • ‎日本語 • ‎한국어
Manuel des extensions MediaWiki
OOjs UI icon advanced.svg
État de la version : stable
Implémentation Balise , ContentHandler
Description Data-driven graphs
Auteur(s) Yuri Astrakhan (Yurik discussion), Dan Andreescu, Frédéric Bolduc
Licence Licence MIT
  • $wgGraphDefaultVegaVer
  • $wgGraphImgServiceUrl
  • $wgGraphAllowedDomains
Traduire l’extension Graph sur translatewiki.net
Vérifier la matrice des utilisations et des versions.
Problèmes Tâches ouvertes · Signaler un bogue

L'extension Graph permet au moyen de la balise <graph> la description de graphiques comme les diagrammes en barre, les camemberts, les frises chronologiques et les histogrammes (démo), dans un format JSON utilisé pour afficher un graphique basé sur Vega.

Informations générales

L'extension Graph donne la possibilité d'intégrer dans une page wiki des graphiques construits avec le puissant outil Vega. Ces graphiques peuvent tout aussi bien être statiques qu'interactifs.

Le moyen le plus simple pour intégrer un graphique est d'utiliser un modèle tout fait comme {{Graph:Chart}}. Ces modèles dissimulent toutes les complexités de Vega. Les utilisateurs avancés peuvent utiliser le Bac à sable de Graph pour développer des graphiques. Le Bac à sable de Graph permet d'associer la syntaxe wiki à JSON.

Liens utiles


  • Si vous utilisez Vagrant , installez avec vagrant roles enable graph --provision
Installation manuelle
  • Requiert l'extension JsonConfig
  • Téléchargez et placez le(s) fichiers (s) dans un répertoire appelé Graph dans votre dossier extensions/.
  • Ajoutez le code suivant à la fin de votre fichier LocalSettings.php :
    wfLoadExtension( 'Graph' );
  • Yes Fait – Accédez à Special:Version sur votre wiki pour vérifier que l'extension a bien été installée.

Additional config setup

If you are looking to replicate a production environment like en.wiki you will need to complete the following steps:


  • 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 Module:Chart locally
  • Copy Module:Plotter/DefaultColors locally.

Exemples de diagrammes

Voir la page de démo pour plus d'exemples et d'astuces d'utilisation.

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 to replace the soon to be decomissioned Graphoid service.

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:

 |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 there is frequently a difference in the redered image width and the actual image width.

 |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}}

Données externes

Le protocole HTTP(S) ne peut pas être utilisé pour obtenir les données du graphiques. À la place, utilisez un des protocoles wiki personnalisés comme wikiraw:, wikiapi:, et d'autres.

Le service Graphoid et l'extension Graph utilisent le paramètre GraphAllowedDomains pour contrôler la résolution de ces protocoles : 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' ],

Problèmes connus et limites

  • Graph extension bugs
  • Graphoid service bugs
  • Fails to implement ISO 8601 timescales so only Gregorian calendars can be used in timelines
  • Image upscaling on most browsers can be blurry by default. Set the appropriate image-rendering property to solve.

Fonctionnement interne

When parsing, the Graph extension expands all template parameters/expressions, and stores the complete graph definitions in the graph_specs page property, using graph hashes for IDs. This means you can easily locate a wiki's graphs with either Special:PageWithProps or the action API.

The graph extension adds HTML to the page where graphs should go, a <div> containing an <img> tag. Exemple :

<div class="mw-wiki-graph-container">
  <img class="mw-wiki-graph-img"
    src="/api/rest_v1/page/graph/png/Extension%3AGraph%2FDemo/1686336/d243aa924db2f82926e0f317217fcce591fe8cd4.png" />

The <img> tag's href attribute points to the #Graphoid service, which provides a static image of the graph.

If the Graph extension is configured for interactivity, and if the client browser has JavaScript enabled and is not a legacy browser to which ResourceLoader does not ship JavaScript, then the client browser renders graphs on the fly. 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. Comme depuis novembre 2015, Wikimedia wikis only enable this interactive rendering for edit preview.

You can configure the Graph extension to always use just the <img> tag, and not add the Vega libraries or graph definition JSON. This mode will not work during editing, since page_props do not get updated until after the save. Once saved, the Graphoid service will be able to access the new graph definition via the action API.

Fonctions de sécurité

<graph> can be configured to disallow referencing untrusted data sources (e.g. Wikimedia only allows data from the Wikimedia sites). It can also send extra headers whenever accessing external data, e.g. Treat-as-Untrusted header that MediaWiki uses to prevent CSRF attacks.


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



If false (default), passes Treat-as-Untrusted:1 header with all graph data requests


A format string to form a backend service request URL for the <img> tag. For example:

$wgGraphImgServiceUrl = "//graphoid.wikimedia.org/%1\$s/v1/png/%2\$s/%3\$s/%4\$s.png";

Would produce this URL:


Parameters will be supplied in this order: 1=server, 2=title, 3=revid, 4=graph-hash-id. All parameters will be escaped with rawurlencode(). If the value is false (default), no <noscript> urls will be generated

Other variables

wgGraphUrlBlacklist variable has been removed in 787d64a11 (7 Dec 2015).

wgGraphDataDomains has been removed in e0813f85a (28 Jan 2016). Use a wgGraphAllowedDomains instead.

wgGraphUserServiceAlways variable has been removed in b735f63ff4b (30 Sep 2015).

Activer l'espace de nom Graph

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,

Service Graphoid

Avertissement Avertissement : WMF is no longer maintaining Graphoid and Graphoid will be undeployed from Wikimedia wikis in the near future.
This section should reference/sync-up with wikitech:Graphoid

Graphoid (git repo) is a node.js service that converts a graph definition into a static PNG image using the same Vega library code that runs in advanced browsers. The reason Graphoid was initially developed was to provide a static image so we wouldn't have to bundle Vega and d3 resource loader modules with every page response. See phab:T211881 for more details. The service is available on the Wikimedia cluster at https://www.mediawiki.org/api/rest_v1/#/Page%20content/get_page_graph_png__title___revision___graph_id_.

You can install it yourself:

$ sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
$ git clone https://gerrit.wikimedia.org/r/mediawiki/services/graphoid
$ cd graphoid
$ npm install
$ npm start

(note: this package is not being maintained (phab:T211881, and installation may fail, see phab:T196001 , phab:T239100. npm i --build-from-source may help.)

The service URLs contain the domain of the page (for example mediawiki.org), service version (v1), the title of the page with the graph (PageTitle), revision ID of the page (12345, but could be 0 for current), and a hash ID of the graph itself (also used in HTML page to identify graph definition), for example:

http://localhost:6927/mediawiki.org/v1/PageTitle/12345/a64b022a8fa5b7fc5e40a2c95cd0a114b2ae1174.png (deprecated url)


You configure the Graph extension to use the Graphoid service in LocalSettings.php with a line like

$wgGraphImgServiceUrl = "//localhost:6927/%1\$s/v1/%2\$s/%3\$s/%4\$s.png"; //deprecated path, older versions only
$wgGraphImgServiceUrl = "//graphoid.wikimedia.org/%1\$s/v1/png/%2\$s/%3\$s/%4\$s.png"; //deprecated path, older versions only

Configure graphoid services

Graph extension workflow

You can further configure the service via its config file.

Module de l'Éditeur Visuel

Depuis l'été 2015, l'extension Graph est également associée au module (ext.graph.VisualEditor) qu permet l'édition d'un graphique dans l'Éditeur Visuel.

Ce module est le fruit d'un projet du Google Summer of Code 2015. Voir phab:T89287 pour plus de détails.

Visulaeditor Graph extension.png

Ce module permet aux utilisateurs de visualiser les graphiques dans l'Éditeur Visuel, contrairement à certaines extensions. De plus, les utilisateurs peuvent ouvrir une boîte de dialogue pour éditer le type de graphique et ses données. L'interface utilisateur offre aussi un moyen d'éditer les paramètres bruts JSON dans l'éditeur visuel, sans passer par l'éditeur de wikitexte, donnant la possibilité aux utilisateurs plus avancés d'ajuster les paramètres qui ne sont pas pris en compte par l'interface.

Cette première étape sert de tremplin au développement de l'édition de graphiques dans l'Éditeur Visuel, et les possibilités d'amélioration et d'extension du module sont nombreuses.

Voir aussi

  • 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