Jump to content

Extensión:Graph

From mediawiki.org
This page is a translated version of the page Extension:Graph and the translation is 34% complete.
Manual de extensiones de MediaWiki
Graph
Estado de lanzamiento: sin mantenimiento
Implementación Etiqueta , ContentHandler
Descripción Gráficos basados en datos
Autor(es)
MediaWiki >= 1.43
Licencia MIT Licencia
Descarga
  • $wgGraphDefaultVegaVer
  • $wgGraphAllowHttp
  • $wgGraphAllowedDomains
Descargas trimestrales 29 (Ranked 103rd)
Wikis públicos que lo utilizan 884 (Ranked 281st)
Traduce la extensión Graph si está disponible en translatewiki.net
Asuntos Tareas abiertas · Reportar un bug

La extensión Graph habilita la etiqueta ‎<graph> para describir visualizaciones de datos tales como diagramas de barras, gráficos circulares, líneas de tiempo e histogramas (véase la demo) en un formato JSON que genera un gráfico basado en Vega.

Información general

La extensión Graph permite integrar gráficos potentes basados en Vega en las páginas wiki. Los gráficos pueden ser interactivos.

La manera más fácil de añadir un gráfico es mediante una plantilla ya preparada como {{Graph:Chart}}. Estas plantillas ocultan todas las complejidades. Los usuarios avanzados pueden usar la zona de pruebas de Graph para desarrollar gráficos. La zona de pruebas de Graph admite la sintaxis de las plantillas wiki además de JSON. La extensión se integra con VisualEditor, proporcionando una sencilla herramienta/asistente que genera gráficos básicos introduciendo los valores directamente en el editor.

Enlaces útiles

Instalación

  • Requiere la extensión JsonConfig
  • Descarga y extrae los archivos en un directorio denominado «Graph» dentro de la carpeta extensions/.
    Developers and code contributors should install the extension from Git instead, using:cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/Graph
  • Añade el siguiente código en la parte final de tu archivo LocalSettings.php :
    wfLoadExtension( 'Graph' );
    
  • Yes Hecho – Navega a Special:Version en el wiki para verificar que la extensión se haya instalado correctamente.


Instalación Vagrant:

  • Si se utiliza Vagrant , instala con vagrant roles enable graph --provision

Configuración adicional

Si estás tratando de replicar un entorno de producción como es.wiki, deberás completar los siguientes pasos:

Depurar gráficos y portar gráficos de Vega 2 a Vega 5

Se proporciona una zona de pruebas en Special:GraphSandbox que funciona de forma similar al editor de gráficos Vega. La herramienta de MediaWiki incluye código de compatibilidad que hace corresponder los esquemas anteriores de Vega a la versión actualmente habilitada. Al insertar un esquema antiguo en el área de texto principal, se incluirá un esquema modificado y modernizado bajo el gráfico donde sea posible.

Similar to vega.github.io/editor, the Vega object can be inspected via the VEGA_DEBUG JavaScript global. See Vega's debugging guide on how to use it.

Migrating schemas from older Vega versions

Previously Graph supported Vega 2. You can paste the JSON of graphs in http://vega.github.io/vega-editor/?mode=vega to see how they previously rendered for comparison with Vega 5.

Special:GraphSandbox (for latest code see the beta cluster version of the sandbox) can be used to map older schemas to new schemas. Copy the old schema into the main textarea and the updated schema will appear in the text area below the graph. Copy the new schema into your code.

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' ],
];

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. Sample:

<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).

License

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

Configuration

wgGraphAllowedDomains

See the section on external data.

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.

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

See also