Gráficas
A chart shows the result of a query as a graphic: lines, columns, areas, pies, scatter plots... You describe it in the screen XML with a chart element, its axes, its series and, optionally, a legend, a tooltip and extra parameters. The chart loads its data from a query, like any other AWE component.
Two engines draw the charts, and the chart XML is the same in both:
| Engine | Library | Notes |
|---|---|---|
| React | Apache ECharts 6.1.0 | Default client of AWE 5. Charts are drawn as SVG |
| AngularJS | Highcharts | Keeps drawing the charts with Highcharts until the AngularJS engine moves to ECharts (issue #775) |
The server does the translation. For every chart it builds the Highcharts chartModel (used by the AngularJS engine) and, next to it, an echartsModel (used by the React engine). The echartsModel is an ECharts option without data and without functions: the client adds the values of the query, and interprets the formats and the other hints that the server sends. The options that you set with chart-parameter are translated too; the ones that have no ECharts counterpart are ignored and reported in the log of the server.
Note: Apache ECharts is open source (Apache License 2.0). Highcharts is open source for non commercial applications. For commercial purposes, you must purchase a license to use it in the AngularJS engine.
The pages about charts are:
- Charts (this page): XML structure, examples of every chart type, actions, differences between the engines.
- Chart formats: the format language of labels, tooltips and axes.
- Chart parameters: the Highcharts options that you can set, and how each one is translated.
Conceptos del gráfico
To get to grasp with how a chart works it is important to understand the various parts or concepts of a chart. Below is an image and a description of the main concepts in a chart. The image was drawn with Highcharts but the parts are the same in both engines.
-
Título: Es el texto que se presentará en la parte superior de un gráfico. Also you can put a subtitle element to describe in more detail the graphic. Más información sobre la estructura XML del elemento gráfico.
-
Series: Conjunto de datos relacionados que se presentan en un gráfico. Un gráfico puede contener una o varias series de datos. See series for more information in XML structure.
-
Tooltip: When hovering over a series or a point on the chart you can get a tooltip that describes the values on that particular part of the chart. See tooltip for more information in XML structure.
-
Legend: The legend shows the data series in the graph and allows for enabling and disabling one or more series. Más información sobre la estructura XML del elemento leyenda.
-
Axis: The x and y-axis of the chart, can also use multiple axes for different data series. Most chart types, like the typical cartesian types line and column, have axes. See axis for more information in XML structure.
Time series with zoom (stock charts)
A chart with stock-chart="true" is meant to show the evolution of a lot of data over time. In the React engine it has a slider under the plot (the navigator) and the x axis can be zoomed with the mouse wheel. The AngularJS engine draws it with Highstock, which adds a range selector, a scrollbar and a navigator.
- Selector fino: Te permite ajustar el rango del gráfico que se muestra.
- Range selector: Allows you to quickly select a range to be shown on the chart or specify the exact interval to be shown. Only in the AngularJS engine.
- Barra de desplazamiento: Permite desplazarse en el gráfico. Only in the AngularJS engine.
- Cruceta: Muestra una línea siguiendo la descripción de un gráfico para leer mejor los resultados del eje x. This functionality can be found in the tooltip options, and it can be used in any chart (it is not enabled by default).
The image above shows Highstock. See the stock chart example for the React engine.
Esqueleto de XML
La estructura básica del gráfico es la siguiente:
<chart id="[Chart Id]" label="[Chart title]" subtitle="[Chart subtitle]" type="[Type chart]"
initial-load="[Initial load]" target-action="[Action]">
<chart-legend layout="[Layout]" align="[Align]" verticalAlign="[Vertical align]" />
<x-axis label="[Label X-Axis]" type="[Type axis]"/>
<y-axis label="[Label Y-Axis]"/>
<chart-tooltip suffix="[Suffix value]" number-decimals="[Decimal numbers]"/>
<chart-serie id="[Serie ID]" x-value="[X-Values]" y-value="[Y-value]" label="[Serie label]" />
<chart-parameter type="[Type parameter]" name="[Name parameter]">
<chart-parameter type="[Type parameter]" name="[Name parameter]" value="[Parameter value]"/>
</chart-parameter>
</chart>
Estructura general del gráfico
Para facilitar el desarrollo, no todas las etiquetas son necesarias.
| Elemento | Uso | Varias instancias | Descripción |
|---|---|---|---|
| chart | Obligatorio | No | Nodo global del gráfico. Describe los atributos generales del gráfico. Título, tipo, qué consulta lo genera, ... |
| chart-legend | Opcional | No | Describe la leyenda del gráfico |
| chart-tooltip | Opcional | No | El tooltip aparece al pasar sobre un punto de una serie. Por defecto, el tooltip muestra los valores del punto y el nombre de la serie |
| x-axis | Obligatorio | Si | Describe el eje X del gráfico |
| y-axis | Obligatorio | Si | Describe el eje Y del gráfico. Es posible tener múltiples ejes y enlazarlos con diferentes series de datos |
| chart-serie | Obligatorio | Si | Una serie es un conjunto de datos. It's represented as list of arrays with two values, [[x1,y1], [x2,y2]]. Cada array es un punto en la serie representado por el eje |
| chart-parameter | Opcional | Si | Extra parameters to overwrite the chart structure. See chart parameters |
The chart element can also hold dependency, context-button and context-separator elements, like the other components. A pie chart has no axes: the axes that the XML declares are not drawn.
Elemento gráfico
El elemento gráfico tiene los siguientes atributos:
| Atributo | Uso | Tipo | Descripción | Valores |
|---|---|---|---|---|
| id | Obligatorio | String | Identificador del gráfico | |
| label | Opcional | String | Es el título del gráfico | Nota: Puedes usar literales i18n |
| subtitle | Opcional | String | Es el subtítulo del gráfico | Nota: Puedes usar literales i18n |
| type | Obligatorio | String | Tipo de gráfico | line, spline, column, column_3d, area, areaspline, arearange, areasplinerange, pie, pie_3d, donut, donut_3d, semicircle, mixed, bubble, scatter. See chart types |
| stock-chart | Opcional | Boolean | Indicador de tipo de gráfico de stock | true or false |
| theme | Opcional | String | Is the name of the Highcharts theme | AngularJS engine only. See Highcharts themes |
| inverted | Opcional | Boolean | Invertir los ejes para que el eje x sea vertical y el eje y sea horizontal. Cuando es true, el eje x es revertido por defecto. | true or false |
| stacking | Opcional | String | Si se deben apilar los valores de cada serie encima de la otra | normal or percent |
| enable-data-labels | Opcional | Boolean | Whether to show the data labels of the points | Defaults to false |
| format-data-labels | Opcional | String | Format string for the data labels. See chart formats | Ej. Punto y con 3 decimales format-data-labels="{y:.3f}" |
| zoom-type | Opcional | String | Decides in what dimensions the user can zoom | xAxis, yAxis or all |
| carga-inicial | Obligatorio | String | Para cargar el gráfico cuando se genera la pantalla | Nota: Solo puede tener el valor 'query' |
| target-action | Obligatorio | String | Es el nombre de la consulta que carga el gráfico | |
| server-action | Opcional | String | Type of server action that loads the chart | |
| max | Opcional | Number | Número de puntos a mostrar | Nota: 0 significa todos los elementos |
| autorefrescar | Opcional | Number | Interval of the automatic reload of the chart | |
| carga automática | Opcional | Boolean | Whether the chart loads its data automatically | |
| style | Opcional | String | CSS classes of the chart | |
| visible | Opcional | Boolean | Whether the chart is visible | |
| ayuda | Opcional | String | Help text of the chart | Nota: Puedes usar literales i18n |
| imagen de ayuda | Opcional | String | Image shown in the help of the chart | |
| carga de íconos | Opcional | String | Define el icono de carga | spinner (por defecto), square, circles, carpet, dots, folding, squarebar, circlebar, cubes, icon, custom, none |
Chart types
| Tipo | Drawn as (React engine) |
|---|---|
line, spline | Lines. spline smooths them |
area, areaspline | Filled lines. areaspline smooths them |
arearange, areasplinerange | Approximated by a filled line (the server logs a warning) |
columna | Vertical bars |
column_3d | Vertical bars, flat (3D is not drawn) |
pie | Pie |
pie_3d | Pie, flat |
donut, donut_3d | Pie with an inner radius (50% by default), flat |
semicircle | Donut that only draws its upper half |
scatter, bubble | Points. bubble uses the z-value of the series as the size |
mixed | The type of each series decides (type of chart-serie). A series without type is a line |
Eje
El elemento eje tiene los siguientes atributos:
| Atributo | Uso | Tipo | Descripción | Valores |
|---|---|---|---|---|
| label | Opcional | String | Es el nombre del eje | Nota: Puedes usar literales i18n |
| label-format | Opcional | String | A format string for the axis label. See chart formats | Defaults to {value}. Ex.: Add unit to axis label-format = "{value} ºC" |
| formatter-function | Opcional | String | Named function to format axis labels | formatCurrencyMagnitude. See named formatters |
| label-rotation | Opcional | Number | Rotación de las etiquetas en grados | Por defecto a 0 |
| type | Opcional | String | El tipo de eje. | linear, logarithmic, datetime or category. Defaults to linear |
| tick-interval | Opcional | Number | El intervalo de las marcas de separación en unidades de eje | In a datetime axis the unit is the millisecond, so an interval of one day is 24 * 3600 * 1000 = 86400000. In a category axis, one label is shown every n categories |
| allow-decimal | Opcional | Boolean | Whether to allow decimals in the ticks of the axis. Cuando se cuentan números enteros, como personas o coincidencias en una página web, los decimales deben evitarse en las etiquetas de las marcas de separación del eje | Defaults to false, so the ticks are integers unless you set true |
| opposite | Opcional | Boolean | Mostrar el eje en el lado opuesto al usual. La normal es en el lado izquierdo para los ejes verticales y el inferior para horizontal, así que los lados opuestos serán de derecha y superior respectivamente | Defaults to false |
An x-axis or y-axis element can hold chart-parameter elements, with the options of the axis scope.
Elemento leyenda
El elemento leyenda tiene los siguientes atributos:
| Atributo | Uso | Tipo | Descripción | Valores |
|---|---|---|---|---|
| label | Opcional | String | Es el título de la leyenda | Nota: Puedes usar literales i18n |
| enabled | Opcional | Boolean | Para activar o desactivar la leyenda en el gráfico | Defaults to false when the chart-legend element is present. Without the element, the legend is shown in charts with axes and hidden in pies and stock charts |
| border-width | Opcional | Number | El ancho del borde dibujado alrededor de la leyenda | Default to 0 |
| layout | Opcional | String | El diseño de los elementos de la leyenda | horizontal or vertical. Defaults to horizontal |
| align | Opcional | String | La alineación horizontal de la caja de la leyenda dentro del área del gráfico | left, center or right. Defaults to center |
| verticalAlign | Opcional | String | La alineación vertical de la caja de leyenda | top, middle or bottom. Defaults to bottom |
| floating | Opcional | Boolean | Cuando la leyenda está flotando, el área de la parcela ignora y se permite colocarla debajo de ella | true or false. Defaults to false |
In a pie chart the legend lists the slices. In the other charts it lists the series and clicking an entry hides and shows the series.
Elemento tooltip
El elemento tooltip tiene los siguientes atributos:
| Atributo | Uso | Tipo | Descripción | Valores |
|---|---|---|---|---|
| enabled | Opcional | Boolean | Para activar o desactivar la descripción en el gráfico | Defaults to true |
| crosshairs | Opcional | String | Muestra el cruce de caminos para conectar los puntos con sus correspondientes valores del eje | xAxis, yAxis or all |
| number-decimals | Opcional | Number | Valor de la descripción de formato ajustando el número de decimales | |
| suffix | Opcional | String | Formatear el valor del tooltip añadiendo una cadena de sufijo | Ej.: suffix = " °C" |
| prefix | Opcional | String | Formatear valor tooltip añadiendo una cadena de prefijo | Ej.: prefix = "Temp. " |
| point-format | Opcional | String | The format of the point's line in the tooltip. See chart formats | Ex.: point-format = '{series.name}: <b>{point.y}</b><br/>' |
| date-format | Opcional | String | For series on a datetime axes, the date pattern of the header of the tooltip | Ex.: date-format = "%Y-%m-%d" |
| shared | Opcional | Boolean | Descripción compartida para múltiples series de gráficos | Defaults to false |
The header and the footer of the tooltip, and the HTML mode, are set with parameters of the tooltip. See HTML tooltips.
Elemento serie
El elemento serie tiene los siguientes atributos:
| Atributo | Uso | Tipo | Descripción | Valores |
|---|---|---|---|---|
| id | Obligatorio | String | Identificador de serie | |
| label | Opcional | String | Es el nombre de la serie. Este valor se muestra en la leyenda | Note: You can use i18n files (locales) |
| type | Opcional | String | Tipo de serie | line, spline, column, bar, pie, area, areaspline, arearange, areasplinerange or scatter. Note: If there are several series of different type, you should set the type attribute of chart element to mixed. A bar series is a horizontal column: it inverts the whole chart |
| color | Opcional | String | Se utiliza para establecer un color para la serie | Nota: Puede usar el nombre de colores o código hexadecimal. Ej.: color = "rojo" o color = "#BF0B23" |
| x-value | Obligatorio | String | Define el valor del punto en el eje x. Corresponde al atributo alias del campo en la consulta | |
| y-value | Obligatorio | String | Define el valor del punto en el eje y. Corresponde al atributo alias del campo en la consulta | |
| z-value | Opcional | String | Defines the value of the point on the z axis (the size of a bubble). Corresponde al atributo alias del campo en la consulta | |
| x-axis | Opcional | Number | Al usar ejes x dobles o múltiples, este número define a qué xAxis está conectada la serie en particular. It refers to the position of the axis | El valor por defecto es 0 |
| y-axis | Opcional | Number | Al usar ejes dobles o múltiples, este número define a qué ejes yAxis está conectada la serie en particular. It refers to the position of the axis | El valor por defecto es 0 |
| drilldown-serie | Opcional | String | Identificador de la serie de desglose | Note: View this example |
| drilldown | Opcional | Boolean | Marcar para indicar si la serie se utiliza en un subgráfico | true or false |
A chart-serie can hold chart-parameter elements, with the options of the series scope.
Elemento parámetro de gráfico
It is used for overwrite values in chart elements. Tiene los siguientes atributos:
| Atributo | Uso | Tipo | Descripción | Valores |
|---|---|---|---|---|
| type | Obligatorio | String | Tipo de parámetro de gráfico | Can be one of string, integer, long, float, double, boolean, array, object or null. |
| name | Obligatorio | String | Nombre del parámetro gráfico | |
| value | Opcional | String | Valor del parámetro gráfico |
The chart element, the axes, the legend, the tooltip and the series accept chart-parameter children. See chart parameters for the options that each engine applies.
Conceptos de series y consultas
In this section, it explains how works the integration between series of graphics and query engine of AWE. A series is a list of points, and a point has an x value and a y value (and a z value in a bubble chart). Each point is a row of the query.
Por lo tanto, debe establecer los valores de x e y para el punto de una serie. For this, exist the serie attributes x-value and y-value.
Estos atributos corresponden al atributo alias del campo en la consulta. Veamos el siguiente ejemplo:
- Código XML del elemento gráfico
<chart id="ChrBarTst" label="CHART_2" type="column_3d" initial-load="query" target-action="TstChrThrDatSrc">
<x-axis label="SCREEN_TEXT_CHART_AXIS_DATES" type="datetime"/>
<y-axis label="Temperaturas (ºC)"/>
<chart-serie id="serie2-1" x-value="dates" y-value="serie1" type="column" label="SCREEN_TEXT_CHART_SERIE_1" />
<chart-serie id="serie2-2" x-value="dates" y-value="serie2" type="column" label="SCREEN_TEXT_CHART_SERIE_2" />
<chart-serie id="serie2-3" x-value="dates" y-value="serie3" type="column" label="SCREEN_TEXT_CHART_SERIE_3" />
</chart>
- Consulta para cargar los datos del gráfico
<!-- GET THREE DATA SERIES WITH DATES -->
<query id="TstChrThrDatSrc" distinct="true">
<table id="HISAweDbs"/>
<field id="HISdat" transform="DATE_MS" function="TRUNCDATE" alias="dates"/>
<computed format="(1/(parseInt(Math.random()*10,10)+1))*10" eval="true" alias="serie1" transform="NUMBER"/>
<computed format="(parseInt(Math.random()*10,10)+1)+2" eval="true" alias="serie2" transform="NUMBER"/>
<computed format="((parseInt(Math.random()*10,10)+1)*2)-4" eval="true" alias="serie3" transform="NUMBER"/>
<order-by field="dates" type="ASC"/>
</query>
In this example, you can see the attribute x-value = "dates" of chart serie is equal to attribute alias in field element and the attribute y-value = "serie1" is equal to alias in the query.
Note: If the axis type is datetime, the chart expects a date as a long value: a JavaScript date timestamp (milliseconds since Jan 1st 1970). AWE provides transform = "DATE_MS".
The series of a chart can also be defined at runtime, without chart-serie elements, with the chart actions.
Note: The values of the points are drawn as the query gives them. The chart does not round them: use
number-decimalsin the tooltip or a format to show a given number of decimals.
Ejemplos
The examples show trimmed screens of the React test application, drawn with ECharts. The values of the series of the test queries are random, so a chart of your application will not look exactly the same. The test screens use Spanish and English texts for their titles and labels.
Every example uses the same query structure: one field with the x value (DATE_MS for dates) and one computed or selected field for each series, as described in Series and queries concepts.
Gráfico de líneas
Type line: the series are drawn as lines with a marker on each point. The color attribute of a series sets its color and zoom-type="xAxis" lets the user zoom the x axis.
<chart id="ChrLinTst" label="SCREEN_TEXT_LINE_CHART" type="line" initial-load="query"
target-action="TstChrTwoSrc" zoom-type="xAxis" max="25">
<chart-legend label="Leyenda" verticalAlign="middle" align="right" border-width="1" />
<x-axis label="Fechas" type="datetime" />
<y-axis label="Temperaturas (ºC)" />
<chart-tooltip crosshairs="xAxis" suffix=" ºC" number-decimals="1" />
<chart-serie id="serie-1" x-value="dates" y-value="serie1" label="Serie 1" color="#0080FF" />
<chart-serie id="serie-2" x-value="dates" y-value="serie2" label="Serie 2" color="#81DAF5" />
</chart>
Note: A
chart-legendelement is disabled unless you setenabled="true", so the legend of this chart is not drawn.
Mixed chart: column, spline and two y axes
Type mixed: each series sets its own type. This chart draws a column series and a spline series, each one on its own y axis (y-axis="0" and y-axis="1"; the second axis is opposite).
<chart id="ChrLinTst" label="SCREEN_TEXT_CHART_TITLE_1" subtitle="Subtitulo grafico 1" type="mixed"
initial-load="query" target-action="TstChrTwoSrc" zoom-type="xAxis" max="30">
<chart-legend label="Leyenda" />
<x-axis label="Fechas" type="datetime" />
<y-axis label="Temperaturas (ºC)" formatter-function="formatCurrencyMagnitude"/>
<y-axis opposite="true" label="Lluvias (mm)" />
<chart-tooltip crosshairs="xAxis" suffix=" ºC" number-decimals="3" shared="true"/>
<chart-serie id="serie-1" y-axis="0" x-value="dates" y-value="serie1" type="column" label="Serie 1" color="#A8E0A6" />
<chart-serie id="serie-2" y-axis="1" x-value="dates" y-value="serie2" type="spline" label="Serie 2" />
</chart>
The tooltip of this chart is shared: it shows the values of all the series at the same x value, with a crosshair. See the tooltip example.
Gráfico de área
Types area and areaspline fill the area under the line. This example uses areaspline and changes the date pattern of the labels of the axis with a chart-parameter.
<chart id="ChrAreTst" label="Grafico 5" type="areaspline" initial-load="query" target-action="TstChrTwoSrcLab" max="16">
<chart-legend align="right" verticalAlign="top" floating="true" />
<x-axis label="Fechas" type="datetime">
<chart-parameter type="object" name="dateTimeLabelFormats">
<chart-parameter type="string" name="day" value="%Y-%m-%d" />
</chart-parameter>
</x-axis>
<y-axis label="Temperaturas (ºC)" />
<chart-tooltip suffix=" ºC" number-decimals="3" />
<chart-serie id="serie1" x-value="dates" y-value="serie1" label="Serie 1" />
<chart-serie id="serie2" x-value="dates" y-value="serie2" label="Serie 2" />
</chart>
Area with a gradient fill
The fill of an area is a linear gradient set in the series (fillColor). The gradient goes from the top to the bottom of the plot. The threshold of -Infinity fills the area from the bottom of the axis, and the markers are styled with plotOptions.area.marker.
<chart id="ChrAdvArea" label="Evolución de la plantilla" type="area" zoom-type="xAxis"
initial-load="query" target-action="ChrAdvAreaSrc">
<chart-legend enabled="false" />
<chart-tooltip number-decimals="0" date-format="%B %Y" crosshairs="xAxis" suffix=" personas" />
<x-axis type="datetime">
<chart-parameter type="object" name="dateTimeLabelFormats">
<chart-parameter type="string" name="month" value="%B %Y" />
</chart-parameter>
<chart-parameter type="string" name="gridLineWidth" value="0.5" />
</x-axis>
<y-axis>
<chart-parameter type="string" name="gridLineWidth" value="0.5" />
</y-axis>
<chart-serie id="staff" x-value="month" y-value="staff" label="Plantilla" color="#8cac41">
<chart-parameter type="object" name="fillColor">
<chart-parameter type="object" name="linearGradient">
<chart-parameter type="integer" name="x1" value="0" />
<chart-parameter type="integer" name="y1" value="0" />
<chart-parameter type="integer" name="x2" value="0" />
<chart-parameter type="integer" name="y2" value="1" />
</chart-parameter>
<chart-parameter type="array" name="stops">
<chart-parameter type="array" name="">
<chart-parameter type="integer" name="" value="0" />
<chart-parameter type="string" name="" value="rgba(140,172,65,0.7)" />
</chart-parameter>
<chart-parameter type="array" name="">
<chart-parameter type="integer" name="" value="1" />
<chart-parameter type="string" name="" value="rgba(140,172,65,0.05)" />
</chart-parameter>
</chart-parameter>
</chart-parameter>
</chart-serie>
<chart-parameter type="object" name="plotOptions">
<chart-parameter type="object" name="area">
<chart-parameter type="integer" name="lineWidth" value="2" />
<chart-parameter type="string" name="threshold" value="-Infinity" />
<chart-parameter type="object" name="marker">
<chart-parameter type="string" name="fillColor" value="#FFFFFF" />
<chart-parameter type="integer" name="lineWidth" value="2" />
<chart-parameter type="string" name="lineColor" value="#0088CC" />
<chart-parameter type="integer" name="radius" value="4" />
</chart-parameter>
</chart-parameter>
</chart-parameter>
</chart>
Column chart
Type column. With the stacking attribute (normal or percent) the series are stacked. The type column_3d is accepted in the XML, but the React engine draws it flat, like this stacked chart:
<chart id="ChrBarTst" label="Grafico 2" subtitle="Subtitulo grafico 2" type="column_3d" stacking="normal"
initial-load="query" target-action="TstChrThrDatSrc" max="21">
<chart-legend layout="vertical" align="right" verticalAlign="middle" />
<x-axis label="SCREEN_TEXT_CHART_AXIS_DATES" type="datetime" />
<y-axis label="Temperaturas (ºC)" />
<chart-tooltip crosshairs="xAxis" suffix=" ºC" number-decimals="3" />
<chart-serie id="serie2-1" x-value="dates" y-value="serie1" type="column" label="SCREEN_TEXT_CHART_SERIE_1" />
<chart-serie id="serie2-2" x-value="dates" y-value="serie2" type="column" label="SCREEN_TEXT_CHART_SERIE_2" />
<chart-serie id="serie2-3" x-value="dates" y-value="serie3" type="column" label="SCREEN_TEXT_CHART_SERIE_3" />
</chart>
The series of a stack are the ones with the same stack parameter (the default stack is shared by all the series).
Stacked columns with rounded corners
The borderRadius of a series (pixels or percentage) rounds the end of the bar that is away from zero, and only in the outermost series of a stack. The padding between columns is set with pointPadding and groupPadding, and the order of the entries of the legend with legendIndex. The y axis uses the formatCurrencyMagnitude formatter.
<chart id="ChrAdvColumns" label="Aportaciones por año" type="column" stacking="normal"
initial-load="query" target-action="ChrAdvColumnsSrc">
<chart-legend enabled="true" />
<chart-tooltip number-decimals="2" suffix=" €" shared="true" />
<x-axis type="category" tick-interval="1" />
<y-axis formatter-function="formatCurrencyMagnitude" tick-interval="500" />
<chart-serie id="company" type="column" x-value="year" y-value="company" label="Empresa" color="#2f6f8f">
<chart-parameter type="string" name="borderRadius" value="30%" />
<chart-parameter type="integer" name="legendIndex" value="2" />
</chart-serie>
<chart-serie id="employee" type="column" x-value="year" y-value="employee" label="Empleado" color="#7fb3c8">
<chart-parameter type="string" name="borderRadius" value="30%" />
<chart-parameter type="integer" name="legendIndex" value="1" />
</chart-serie>
<chart-parameter type="object" name="plotOptions">
<chart-parameter type="object" name="column">
<chart-parameter type="float" name="pointPadding" value="0.05" />
<chart-parameter type="float" name="groupPadding" value="0.05" />
</chart-parameter>
</chart-parameter>
</chart>
Bar chart and pyramid
A bar chart is a column chart turned on its side. There are two ways to get it: a series of type bar, or inverted="true" in the chart. In both cases the x axis is vertical, and the y axis is horizontal (the first category or the oldest date is at the top).
The pyramid is a bar chart with two series that share a stack, a second x axis on the opposite side, and negative and positive values formatted with a condition. Two helper series (dummyMax and dummyMin, of type scatter) are hidden from the legend and from the mouse: they only extend the range of the axis.
<chart id="ChrAdvPyramid" label="Pirámide salarial" type="column" inverted="true"
initial-load="query" target-action="ChrAdvPyramidSrc">
<chart-legend enabled="true" />
<chart-tooltip shared="false">
<!-- html tooltip: see Chart formats -->
</chart-tooltip>
<x-axis type="category" />
<x-axis type="category" opposite="true" />
<y-axis>
<chart-parameter type="object" name="labels">
<chart-parameter type="string" name="format"
value="{#if (gt value 0)}{multiply value 0.001}k{else}{multiply value -0.001}k{/if}" />
</chart-parameter>
<chart-parameter type="string" name="gridLineWidth" value="0" />
</y-axis>
<chart-serie id="men" type="column" x-value="age" y-value="men" label="Hombres" color="#4a7dbf">
<chart-parameter type="string" name="stack" value="salary" />
<chart-parameter type="float" name="pointPadding" value="0" />
<chart-parameter type="float" name="groupPadding" value="0.1" />
<chart-parameter type="integer" name="borderRadius" value="20" />
<chart-parameter type="object" name="dataLabels">
<chart-parameter type="boolean" name="enabled" value="true" />
<chart-parameter type="string" name="format"
value="{#if (gt y 0)}{y:,.0f}€{else}{(multiply y -1):,.0f}€{/if}" />
</chart-parameter>
</chart-serie>
<chart-serie id="women" type="column" x-value="age" y-value="women" label="Mujeres" color="#d9789b" x-axis="1">
<chart-parameter type="string" name="stack" value="salary" />
<!-- same parameters as the men series -->
</chart-serie>
<chart-serie id="dummyMax" type="scatter" x-value="age" y-value="dummyMax" label="max" color="transparent">
<chart-parameter type="boolean" name="showInLegend" value="false" />
<chart-parameter type="boolean" name="enableMouseTracking" value="false" />
<chart-parameter type="object" name="marker">
<chart-parameter type="boolean" name="enabled" value="false" />
</chart-parameter>
</chart-serie>
<chart-serie id="dummyMin" type="scatter" x-value="age" y-value="dummyMin" label="min" color="transparent">
<chart-parameter type="string" name="linkedTo" value=":previous" />
<!-- same parameters as dummyMax -->
</chart-serie>
</chart>
Pie chart
Type pie. The legend lists the slices. enable-data-labels shows the label of each slice, and its text is set with format-data-labels (see chart formats). A pie has no axes, so the axes that the XML declares are not drawn.
<chart id="ChrPieTst" label="Grafico 6" type="pie" initial-load="query" enable-data-labels="true"
format-data-labels="<b>{point.name}</b>: {point.percentage:.1f} %"
target-action="TstChrPieDrillSrc" max="5">
<chart-legend enabled="true" />
<x-axis label="Themes" />
<y-axis label="Percent (%)" />
<chart-tooltip suffix=" %" number-decimals="2" />
<chart-serie id="serie1" x-value="names" y-value="serie1" label="Themes" />
<chart-parameter type="object" name="plotOptions">
<chart-parameter type="object" name="pie">
<chart-parameter type="string" name="size" value="75%" />
</chart-parameter>
</chart-parameter>
</chart>
Pie with its own colors
The colors parameter sets the palette of the chart. With colorByPoint every slice takes a color, and allowPointSelect lets the user select a slice with a click. This chart has the type pie_3d, which is drawn flat.
<chart id="ChrAdvPie3d" label="Plantilla por categoría" type="pie_3d" enable-data-labels="true"
initial-load="query" target-action="ChrAdvPieSrc">
<chart-legend enabled="true" />
<chart-tooltip number-decimals="0" suffix=" personas" />
<chart-serie id="cat" x-value="category" y-value="people" label="Personas" />
<chart-parameter type="array" name="colors">
<chart-parameter type="string" name="" value="rgba(201,229,134,0.9)" />
<chart-parameter type="string" name="" value="rgba(140,172,65,0.9)" />
<!-- ... -->
</chart-parameter>
<chart-parameter type="object" name="plotOptions">
<chart-parameter type="object" name="series">
<chart-parameter type="boolean" name="colorByPoint" value="true" />
<chart-parameter type="boolean" name="allowPointSelect" value="true" />
</chart-parameter>
<chart-parameter type="object" name="pie">
<chart-parameter type="object" name="dataLabels">
<chart-parameter type="string" name="connectorColor" value="rgba(128,128,128,0.7)" />
</chart-parameter>
</chart-parameter>
</chart-parameter>
</chart>
Donut chart
Types donut and donut_3d draw a pie with an inner radius (50% by default). plotOptions.pie.size is the outer radius and plotOptions.pie.innerSize the inner radius, relative to size. The 3D type is drawn flat.
<chart id="ChrDonutTst" label="Grafico 7" type="donut_3d" initial-load="query" target-action="TstChrPieSrc" max="5">
<chart-legend enabled="true" />
<x-axis label="Themes" />
<y-axis label="Percent (%)" />
<chart-tooltip suffix=" %" number-decimals="2" />
<chart-serie id="serie1" x-value="names" y-value="serie1" label="Themes" />
<chart-parameter type="object" name="plotOptions">
<chart-parameter type="object" name="pie">
<chart-parameter type="string" name="size" value="75%" />
<chart-parameter type="string" name="innerSize" value="40%" />
</chart-parameter>
</chart-parameter>
</chart>
Gráfico de semicírculo
Type semicircle draws only the upper half of a donut. The labels are written inside the slices (a negative dataLabels.distance), and the title is moved to the middle of the chart with the title parameters. Like in Highcharts, the center and the size of the semicircle are measured in the plot area, which leaves out the legend, so the title sits in the hole.
<chart id="ChrSemiCircleTst" label="Grafico 8" type="semicircle" enable-data-labels="true"
initial-load="query" target-action="TstChrPieSrc" max="5">
<chart-legend enabled="true" />
<x-axis label="Themes" />
<y-axis label="Percent (%)" />
<chart-tooltip suffix=" %" number-decimals="2" />
<chart-serie id="serie1" x-value="names" y-value="serie1" label="Themes" />
<chart-parameter type="object" name="title">
<chart-parameter type="string" name="align" value="center" />
<chart-parameter type="string" name="verticalAlign" value="middle" />
<chart-parameter type="integer" name="y" value="50" />
</chart-parameter>
<chart-parameter type="object" name="plotOptions">
<chart-parameter type="object" name="pie">
<chart-parameter type="string" name="size" value="75%" />
<chart-parameter type="string" name="innerSize" value="40%" />
<chart-parameter type="object" name="dataLabels">
<chart-parameter type="boolean" name="enabled" value="true" />
<chart-parameter type="integer" name="distance" value="-20" />
<chart-parameter type="object" name="style">
<chart-parameter type="string" name="fontWeight" value="bold" />
<chart-parameter type="string" name="color" value="white" />
<chart-parameter type="string" name="textShadow" value="0px 1px 2px black" />
</chart-parameter>
</chart-parameter>
</chart-parameter>
</chart-parameter>
</chart>
Drilldown
A series with drilldown-serie opens another series when the user clicks one of its points. The target series sets drilldown="true" and is not drawn until it is opened. A Back to Themes link (the name of the first series) at the top left of the chart returns to the first level (the text comes from the drillUpText of the chart text files). The keys parameter of the first series binds the values of each point to the name, the y value and the drilldown target.
<chart id="ChrPieTst" label="Grafico 6" type="pie" initial-load="query" enable-data-labels="true"
format-data-labels="<b>{point.name}</b>: {point.percentage:.1f} %"
target-action="TstChrPieDrillSrc" max="5">
<chart-legend enabled="true" />
<x-axis label="Themes" />
<y-axis label="Percent (%)" />
<chart-tooltip suffix=" %" number-decimals="2" />
<chart-serie id="serie1" x-value="names" y-value="serie1" label="Themes" drilldown-serie="serie1_1">
<chart-parameter type="array" name="keys">
<chart-parameter type="string" value="name" name=""/>
<chart-parameter type="string" value="y" name=""/>
<chart-parameter type="string" value="drilldown" name=""/>
</chart-parameter>
</chart-serie>
<chart-serie id="serie1_1" drilldown="true" x-value="names" y-value="subserie1" label="SubThemes" />
</chart>
The query returns the values of both levels in the same row:
<query id="TstChrPieDrillSrc" distinct="true">
<table id="AweThm"/>
<field id="Nam" alias="names"/>
<computed format="parseInt(Math.random()*100,10)" eval="true" alias="serie1" transform="NUMBER"/>
<computed format="(parseInt(Math.random()*100,10))+2" eval="true" alias="subserie1" transform="NUMBER"/>
</query>
Scatter chart
Type scatter: one point for each row, with no line. The x and y values are numbers or dates.
<chart id="ChrScaTst" label="Grafico 10" subtitle="Subtitulo grafico 10" type="scatter" initial-load="query"
target-action="TstChrOneSrcThrAxs" max="21">
<chart-legend layout="vertical" align="right" verticalAlign="middle" />
<x-axis label="SCREEN_TEXT_CHART_AXIS_DATES" type="datetime" />
<y-axis label="Temperaturas (ºC)" />
<chart-tooltip suffix=" ºC" number-decimals="3" />
<chart-serie id="serie2-1" x-value="Ord" y-value="serie1_1" z-value="serie1_2" label="SCREEN_TEXT_CHART_SERIE_1" />
</chart>
Bubble chart
Type bubble: a scatter chart where the z-value of the series gives the size of each bubble. The range of the sizes is set with minSize and maxSize, and the data labels can show the z value with {point.z}.
<chart id="ChrAdvBubble" label="Rentabilidad frente a riesgo" type="bubble" initial-load="query"
target-action="ChrAdvBubbleSrc">
<chart-legend enabled="false" />
<x-axis label="Riesgo (%)" />
<y-axis label="Rentabilidad (%)" label-format="{value:.2f}" />
<chart-serie id="funds" x-value="risk" y-value="return" z-value="weight" label="Fondos" />
<chart-parameter type="object" name="plotOptions">
<chart-parameter type="object" name="series">
<chart-parameter type="object" name="dataLabels">
<chart-parameter type="boolean" name="enabled" value="true" />
<chart-parameter type="string" name="format" value="{point.z}" />
</chart-parameter>
</chart-parameter>
<chart-parameter type="object" name="bubble">
<chart-parameter type="integer" name="minSize" value="10" />
<chart-parameter type="integer" name="maxSize" value="40" />
</chart-parameter>
</chart-parameter>
</chart>
Without minSize and maxSize the sizes go from 10 to 50 pixels:
Stock chart with zoom
With stock-chart="true" the chart is meant for long time series. The React engine adds a slider (the navigator) under the plot, a zoom of the x axis with the mouse wheel, and shows no legend by default.
<chart style="expand-3x" id="ChrStockTst" label="Grafico 4" stock-chart="true" zoom-type="xAxis" type="line"
initial-load="query" target-action="TstChrThrDatSrcHor" max="30">
<x-axis label="Fechas" type="datetime" />
<y-axis label="Temperaturas (ºC)" label-format="{value} ºC"/>
<chart-tooltip suffix=" ºC" number-decimals="2" />
<chart-serie id="serie1" x-value="dates" y-value="serie1" label="Serie 1" />
</chart>
zoom-type (xAxis, yAxis or all) adds the zoom of the axes to any chart, not only to the stock ones.
Chart actions
The server can change a chart from a service, with client actions. The actions are built with the classes of com.almis.awe.builder.client.chart and are listed in the actions page:
| Action | Builder | Effect |
|---|---|---|
add-chart-series | AddChartSeriesActionBuilder | Adds series (a series with the same id is replaced) |
remove-chart-series | RemoveChartSeriesActionBuilder | Removes the series with the given ids |
replace-chart-series | ReplaceChartSeriesActionBuilder | Replaces all the series |
add-points | AddPointsActionBuilder | Adds the rows of a DataList to the values of the chart |
The series that the actions carry are ChartSerie objects, with the id, the name, the x-value and y-value names and the points. The server translates each one to ECharts, as it does with the chart-serie elements of the XML, and sends the translation with the action. The chart does not need to declare series in its XML: the screen of the example has no chart-serie elements.
public ServiceData replaceSeriesChart(List<String> userList) {
List<ChartSerie> series = new ArrayList<>();
for (String user : userList) {
ChartSerie serie = new ChartSerie();
serie.setId(user);
serie.setName(user);
serie.setXValue("month");
serie.setYValue(user + "-y");
serie.setData(months.stream()
.map(month -> new ChartSeriePoint(factory.textNode(month), factory.numberNode(random.nextInt(11))))
.toList());
series.add(serie);
}
return new ServiceData().addClientAction(new ReplaceChartSeriesActionBuilder("ChrLinTst", series).build());
}
The ChrTstDynamicSeries screen of the test application has three buttons that call services like this one (add, remove and replace series).
Dependencies
A dependency with target-type="chart-options" changes the options of a chart at runtime. For example, to synchronize the zoom of two charts:
<dependency source-type="formule" target-type="chart-options" formule="{zoom: {x: {min: [xMin],max: [xMax]}}}">
<dependency-element id="ChrStockTst" attribute="xMin" alias="xMin" optional="true"/>
<dependency-element id="ChrStockTst" attribute="xMax" alias="xMax" optional="true"/>
<dependency-element id="ChrStockTst" event="zoom"/>
</dependency>
The result of the formula is a Highcharts options object, so it is applied only by the AngularJS engine. The React engine does not apply it: the client logs a warning in the browser console (The 'chart-options' dependency is not applied to charts drawn with ECharts) and leaves the chart as it is. The other dependencies of a chart (visibility, attributes, reload...) work in both engines. See dependencies.
Differences between the engines
| Feature | React (ECharts) | AngularJS (Highcharts) |
|---|---|---|
3D types (column_3d, pie_3d, donut_3d) | Drawn flat | Drawn in 3D |
chart-parameter options | Only the translated options; the rest are ignored and logged | Any option of the Highcharts API |
chart-options dependency | Not applied (warning in the console) | Applied |
theme attribute (Highcharts themes) | Ignored. The look comes from the theme of the application | Applied |
| Default palette | The Highcharts 11 palette, for the series without color | The Highcharts palette, or the one of the theme |
| Dark mode | The charts follow the theme of the application (see below) | Highcharts themes (theme attribute) |
| Stock charts | Slider and zoom with the mouse wheel | Highstock: navigator, range selector, scrollbar |
| Printing | Image drawn by the SVG renderer of ECharts | Highcharts export |
| Chart texts | Files src/i18n/charts/charts-<language>.json | Texts of the AngularJS client |
Known limits of the React engine
- 3D charts are flat. The 3D types are accepted, so existing screens keep working, but the depth is not drawn.
- Colors. When the XML gives no colors, the series take the colors of the Highcharts 11 default palette (
#2caffe,#544fc5,#00e272,#fe6a35,#6b8abc,#d568fb,#2ee0ca,#fa4b42,#feb56a,#91e8e1). Set thecolorof the series, or thecolorsparameter of the chart, to use your own. - Dark theme. The chart reads the theme of the application when it is created, and draws itself with light or dark colors. If the user changes the theme while the screen is open, the chart picks the new theme when it is created again (for example when the screen is opened again or the language changes).
- Drilldown and printing. Printing a chart that is drilled down prints the top level.
- Raw values. The values are drawn as the query gives them: nothing is rounded unless a format or
number-decimalssays so. - Highcharts options. Options without an ECharts counterpart are ignored. Check the log of the server, which reports each one once (see chart parameters).
- Highcharts themes. The
themeattribute applies only to the AngularJS engine. - Range types.
arearangeandareasplinerangeare approximated by a filled line.
Highcharts themes (AngularJS engine)
Note: This section applies only to the AngularJS engine. The React engine ignores the
themeattribute.
The AngularJS engine and the Highcharts library allow to change the style easily. Hay algunos temas por defecto. Just set the attribute theme of the chart element with the name of the theme.
La lista de temas disponible es:
- dark-unica
- dark-green
- dark-blue
- gray
- grid
Creando tu propio tema
Here is a simple example to show the process:
/**
* Theme for Highcharts JS
*/
Highcharts.theme["your-theme"] = {
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572',
'#FF9655', '#FFF263', '#6AF9C4'],
chart: {
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(255, 255, 255)'],
[1, 'rgb(240, 240, 255)']
]
},
},
title: {
style: {
color: '#000',
font: 'bold 16px "Trebuchet MS", Verdana, sans-serif'
}
},
subtitle: {
style: {
color: '#666666',
font: 'bold 12px "Trebuchet MS", Verdana, sans-serif'
}
},
legend: {
itemStyle: {
font: '9pt Trebuchet MS, Verdana, sans-serif',
color: 'black'
},
itemHoverStyle:{
color: 'gray'
}
}
};
Nota: Debe añadir el nuevo nombre de archivo en scripts.xml en su proyecto.
Printing and server rendering
Printing in the React engine. When the user prints a screen with a chart, the client draws an image of the chart apart from the screen, with the SVG renderer of ECharts, in light colors and with the size of the page. The image is drawn from the top level of the chart, even when the user has drilled down.
Rendering on the server. The ChartService described below is independent of the engine of the browser: it builds the Highcharts model of the chart and sends it to a Highcharts export server, which returns an SVG image. It still needs the export server (highcharts.server.url).
Servicio de exportación de gráficas
Highcharts tiene un servidor de exportación que le permite generar gráficas de alta calidad en el servidor:
https://www.highcharts.com/docs/export-module/setting-up-the-server
Hemos desarrollado un nuevo servicio de renderizado que le permite generar cartas en formato SVG usando este servidor de exportación y cartas AWE.
Definiendo gráficos
Definir un gráfico que se generará en el servidor es similar a definir un gráfico que se mostrará en un navegador.
Usted define una pantalla y dentro del gráfico, como se muestra antes. Esta pantalla puede estar o no en la aplicación, no importa.
Los gráficos definidos para ser generados en el servidor no necesitan atributos server-action y target-action, ya que los datos se van a pasar como parámetros.
Uso
Hay un nuevo servicio diseñado para generar gráficas en el lado del servidor, llamado ChartService. Este servicio tiene dos métodos que permiten al desarrollador generar cartas usando una sola fuente de datos o múltiples fuentes de datos:
Renderiza un gráfico con un solo Lista de datos
El método de render chart (con una sola lista de datos) genera una gráfica usando solo una lista de datos como fuente de datos.
public String renderChart(String screenName, String chartName, DataList data) throws AWException
screenNamees el nombre del archivo de pantalla donde está el gráficochartNamees el id `` del gráfico que se generarádataes lalista de datosorigen
Este método devolverá un gráfico en formato SVG+XML (o AWException si hay un error).
Procesar un gráfico con múltiples listas de datos
El método de procesamiento de cartas (con un mapa de listas de datos) genera un gráfico usando múltiples listas de datos.
public String renderChart(String screenName, String chartName, Map<String, DataList> datasources) throws AWException
screenNamees el nombre del archivo de pantalla donde está el gráficochartNamees el id `` del gráfico que se generarádatasourceses un mapa de String y DataList que contendrá todas las fuentes de datos.
Este método devolverá un gráfico en formato SVG+XML (o AWException si hay un error).
Uno de los datos debe llamarse principal, y será el predeterminado. el resto coincidirá con un parámetro de datos definido en la serie que debería seleccionar los datos. For example, this serie would pick the DataList inside the detail map key:
<chart-serie id="data" x-value="name" y-value="value"/>
<chart-serie id="detail" x-value="name" y-value="value">
<chart-parameter type="string" name="datasource" value="detail"/>
</chart-serie>
el mapa correspondiente para esta serie debe ser:
Map<String, DataList> datasources = new HashMap<>();
datasources.put("main", mainDataList);
datasources.put("detail", detailDataList);
La primera serie (data) elegirá los datos definidos en clave principal y la segunda serie (detalle) elegirá los datos definidos en la tecla detalle
Procesar servidor
Puede configurar el servidor de renderizado en el archivo application.properties actualizando la propiedad highcharts.server.url:
################################################
# Chart properties
################################################
highcharts.server.url=http://export.highcharts.com
El servidor de exportación predeterminado apunta al servidor de exportación de Highchart: http://export.highcharts.com
Upgrading to AWE 5
In AWE 5 the React engine draws the charts with Apache ECharts 6.1.0 instead of Highcharts. The AngularJS engine keeps drawing them with Highcharts until it moves to ECharts (issue #775).
The chart XML does not change. The server translates the chart, its axes, series and chart-parameter elements into an ECharts model, and logs a warning (once per option) for every option it cannot translate. Check these points when you upgrade an application that uses the React engine:
- Review the log of the server. Open every screen with a chart and look for warnings that start with
Highcharts chart-parameter. Each one is an option that the React engine ignores. See chart parameters for the options that are translated. - Custom code that imports Highcharts. The React client no longer depends on
highchartsnor onhighcharts-react-official. A custom component of your application that imports them has to declare them in its ownpackage.json(check the Highcharts licence) or move to ECharts, which the client already provides. .highcharts-*CSS rules. The charts are no longer drawn by Highcharts, so these rules do not match anything in the React engine. Colors, fonts and borders come from the XML (chart-parameter) and from the theme. The dark mode of the application is applied to the charts automatically, when the chart is created.- Palette. The series without a color of their own keep the Highcharts 11 default palette. Set
colorin the series or thecolorsparameter in the chart to change it. - Highcharts themes. The
themeattribute is ignored by the React engine. If a theme gave colors or fonts to your charts, set them in the XML. - 3D charts (
column_3d,pie_3d,donut_3d) are drawn flat. chart-optionsdependency. Its result is a Highcharts options object. It is not applied to the charts drawn with ECharts and the client logs a warning in the browser console.- Formats. The format strings of Highcharts 11 (
{point.y:.2f},{#if ...}, the date patterns of%Y-%m-%d...) work as before, see chart formats. Number specifications other than.Nfand,.Nfare written as the raw value, and the values are never rounded unless a format asks for it. - Printing. The charts are printed from an image drawn by ECharts. A drilled-down chart prints its top level.
- Chart texts. The language files of the chart texts are
src/i18n/charts/charts-<language>.jsonin the React client, and they only hold the texts that the charts use:noData,drillUpText,decimalPoint,thousandsSep,months,shortMonthsandweekdays. Copy your customizations to those files. - Server rendering.
ChartServicestill uses the Highcharts export server and the Highcharts model of the chart, sohighcharts.server.urlis still needed for it.