Modulo:Graph: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
Yurik (discussione | contributi)
marked all graphs as being vega 1.0. Please upgrade to 2.0
Yurik (discussione | contributi)
updated to latest version from w:de:Module:Graph
Riga 1:
-- version 2016-01-06 _PLEASE UPDATE when modifying anything_
local p = {}
local cfg = mw.loadData( 'Modulo:Chart/Configurazione' );
local getArgs = require('Module:Arguments').getArgs
local errors = { }
 
local baseMapDirectory = "Module:Graph/"
local function dump(t, ...)
local args = {...}
for _, s in ipairs(args) do
table.insert(t, s)
end
end
 
local function numericArray(csv)
-- ===============================================================================
if not csv then return end
-- Add error message to errors list, mgs_key must be a error key listed in
 
-- cfg.errors_key, args is an optional array of string
local list = mw.text.split(csv, "%s*,%s*")
-- ===============================================================================
local result = {}
local function add_error(msg_key, args)
local isInteger = true
local msg = cfg.errors_key[msg_key]
for i = 1, #list do
if not msg then msg = cfg.errors_key.unknown_error end
result[i] = tonumber(list[i])
if args then
if not result[i] then return end
errors[#errors+1] = mw.ustring.format(msg, unpack(args))
if isInteger then
else
local int, frac = math.modf(result[i])
errors[#errors+1] = msg
isInteger = frac == 0.0
end
end
end
return result, isInteger
end
 
local function stringArray(csv)
-- ===============================================================================
if not csv then return end
-- Consolidate errors messages and add error category
 
-- ===============================================================================
return mw.text.split(csv, "%s*,%s*")
local function errors_output(nocat)
if #errors > 0 then
local out = string.format('<strong class="error">%s</strong>', table.concat(errors, "; "))
if nocat or not cfg.uncategorized_namespaces[mw.title.getCurrentTitle().ns] then
out = out .. '[[Category:' .. cfg.errors_category .. ']]'
end
return out
end
return ''
end
 
local function isTable(t) return type(t) == "table" end
-- ===============================================================================
 
-- Return true if val is not nil and is a string in the array cfg.yes_values
function p.map(frame)
-- ===============================================================================
-- map path data for geographic objects
local function return_yes_value(val)
local basemap = frame.args.basemap or "WorldMap-iso2.json"
return val and cfg.yes_values[mw.ustring.lower(val)]
-- scaling factor
local scale = tonumber(frame.args.scale) or 100
-- map projection, see https://github.com/mbostock/d3/wiki/Geo-Projections
local projection = frame.args.projection or "equirectangular"
-- defaultValue for geographic objects without data
local defaultValue = frame.args.defaultValue
local scaleType = frame.args.scaleType or "linear"
-- minimaler Wertebereich (nur für numerische Daten)
local domainMin = tonumber(frame.args.domainMin)
-- maximaler Wertebereich (nur für numerische Daten)
local domainMax = tonumber(frame.args.domainMax)
-- Farbwerte der Farbskala (nur für numerische Daten)
local colorScale = frame.args.colorScale or "category10"
-- show legend
local legend = frame.args.legend
-- format JSON output
local formatJson = frame.args.formatjson
 
-- map data are key-value pairs: keys are non-lowercase strings (ideally ISO codes) which need to match the "id" values of the map path data
local values = {}
local isNumbers = nil
for name, value in pairs(frame.args) do
if mw.ustring.find(name, "^[^%l]+$") then
if isNumbers == nil then isNumbers = tonumber(value) end
local data = { id = name, v = value }
if isNumbers then data.v = tonumber(data.v) end
table.insert(values, data)
end
end
if not defaultValue then
if isNumbers then defaultValue = 0 else defaultValue = "silver" end
end
 
-- create highlight scale
local scales
if isNumbers then
if colorScale == "category10" or colorScale == "category20" then else colorScale = stringArray(colorScale) end
scales =
{
{
name = "color",
type = scaleType,
___domain = { data = "highlights", field = "v" },
range = colorScale,
nice = true
}
}
if domainMin then scales[1].domainMin = domainMin end
if domainMax then scales[1].domainMax = domainMax end
 
local exponent = string.match(scaleType, "pow%s+(%d+%.?%d+)") -- check for exponent
if exponent then
scales[1].type = "pow"
scales[1].exponent = exponent
end
end
 
-- create legend
if legend then
legend =
{
{
fill = "color",
offset = 120,
properties =
{
title = { fontSize = { value = 14 } },
labels = { fontSize = { value = 12 } },
legend =
{
stroke = { value = "silver" },
strokeWidth = { value = 1.5 }
}
}
}
}
end
 
-- get map url
local basemapUrl
if (string.sub(basemap, 1, 7) == "http://") or (string.sub(basemap, 1, 8) == "https://") or (string.sub(basemap, 1, 2) == "//") then
basemapUrl = basemap
else
-- if not a (supported) url look for a colon as namespace separator. If none prepend default map directory name.
if not string.find(basemap, ":") then basemap = baseMapDirectory .. basemap end
basemapUrl = mw.title.new(basemap):fullUrl("action=raw")
end
 
local output =
{
version = 2,
width = 1, -- generic value as output size depends solely on map size and scaling factor
height = 1, -- ditto
data =
{
{
-- data source for the highlights
name = "highlights",
values = values
},
{
-- data source for map paths data
name = "countries",
url = basemapUrl,
format = { type = "topojson", feature = "countries" },
transform =
{
{
-- geographic transformation ("geopath") of map paths data
type = "geopath",
value = "data", -- data source
scale = scale,
translate = { 0, 0 },
projection = projection
},
{
-- join ("zip") of mutiple data source: here map paths data and highlights
type = "lookup",
keys = { "id" }, -- key for map paths data
on = "highlights", -- name of highlight data source
onKey = "id", -- key for highlight data source
as = { "zipped" }, -- name of resulting table
default = { v = defaultValue } -- default value for geographic objects that could not be joined
}
}
}
},
marks =
{
-- output markings (map paths and highlights)
{
type = "path",
from = { data = "countries" },
properties =
{
enter = { path = { field = "layout_path" } },
update = { fill = { field = "zipped.v" } },
hover = { fill = { value = "darkgrey" } }
}
}
},
legends = legend
}
if (scales) then
output.scales = scales
output.marks[1].properties.update.fill.scale = "color"
end
 
local flags
if formatJson then flags = mw.text.JSON_PRETTY end
return mw.text.jsonEncode(output, flags)
end
 
local function deserializeXData(serializedX, xType, xMin, xMax)
-- ===============================================================================
local x
-- Return true if val is not nil and is a string in the array cfg.no_value
 
-- ===============================================================================
if not xType or xType == "integer" or xType == "number" then
local function return_no_value(val)
local isInteger
return val and cfg.no_values[mw.ustring.lower(val)]
x, isInteger = numericArray(serializedX)
if x then
xMin = tonumber(xMin)
xMax = tonumber(xMax)
if not xType then
if isInteger then xType = "integer" else xType = "number" end
end
else
if xType then error("Numbers expected for parameter 'x'") end
end
end
if not x then
x = stringArray(serializedX)
if not xType then xType = "string" end
end
 
return x, xType, xMin, xMax
end
 
local function deserializeYData(serializedYs, yType, yMin, yMax)
-- ===============================================================================
local y = {}
-- Return an array of numbers splitting a string at ","
local areAllInteger = true
-- For localization purpose check for the presence of an alternative separator
 
-- and alternative symbol for decimal separator
for yNum, value in pairs(serializedYs) do
-- ===============================================================================
local yValues
local function numericArray(csv, default_empty)
if not yType or yType == "integer" or yType == "number" then
if not csv then return end
local isInteger
if default_empty == nil then default_empty = 'x' end
yValues, isInteger = numericArray(value)
local list = {}
if yValues then
-- check for local separator character instead of ","
areAllInteger = areAllInteger and isInteger
if mw.ustring.find(csv, cfg.separator.list) then
else
list = mw.text.split(mw.ustring.gsub(csv, "%s", ""), cfg.separator.list)
if yType then
for index,v in ipairs(list) do
error("Numbers expected for parameter '" .. name .. "'")
list[index] = mw.ustring.gsub(v, cfg.separator.decimal, ".")
else
end
return deserializeYData(serializedYs, "string", yMin, yMax)
else
end
list = mw.text.split(mw.ustring.gsub(csv, "%s", ""), ",")
end
end
-- build output array replacing empty value with a "x"
if not yValues then yValues = stringArray(value) end
local result = {}
 
for i, val in ipairs(list) do
y[yNum] = yValues
if val == '' then
end
result[i] = 'x'
if not yType then
else
if areAllInteger then yType = "integer" else yType = "number" end
result[i] = tonumber(val)
end
if yType == "integer" or yType == "number" then
end
yMin = tonumber(yMin)
return result
yMax = tonumber(yMax)
end
 
return y, yType, yMin, yMax
end
 
local function convertXYToManySeries(x, y, xType, yType, seriesTitles)
-- ===============================================================================
local data =
-- Return an array of string splitting at ","
{
-- ===============================================================================
name = "chart",
local function stringArray(csv)
format =
if not csv then return end
{
local t = {}
type = "json",
for s in mw.text.gsplit(csv, ",") do
parse = { x = xType, y = yType }
t[#t+1] = mw.text.trim(s)
},
end
values = {}
return t
}
for i = 1, #y do
for j = 1, #x do
if j <= #y[i] then table.insert(data.values, { series = seriesTitles[i], x = x[j], y = y[i][j] }) end
end
end
return data
end
 
local function convertXYToSingleSeries(x, y, xType, yType, yNames)
local data = { name = "chart", format = { type = "json", parse = { x = xType } }, values = {} }
 
for j = 1, #y do data.format.parse[yNames[j]] = yType end
-- ==============================================================================
 
-- Return true if t is a table
for i = 1, #x do
-- ===============================================================================
local functionitem isTable(t)= { x = x[i] }
for j = 1, #y do item[yNames[j]] = y[j][i] end
return type(t) == "table"
end
 
table.insert(data.values, item)
-- ==============================================================================
end
-- Extend table replicating content
return data
-- ==============================================================================
local function extend_table(t, new_len)
if #t >= new_len then return t end
local pos = 1
local old_len = #t
for i = #t+1, new_len do
t[i] = t[pos]
pos = pos + 1
if pos > old_len then pos = 1 end
end
return t
end
 
local function getXScale(chartType, stacked, xMin, xMax, xType)
-- ==============================================================================
if chartType == "pie" then return end
-- Generate a color palette from the name (must be in cfg.colors_palette)
 
-- with minimal length len
local xscale =
-- ==============================================================================
{
local function generate_color_palette(palette, len)
name = "x",
if not cfg.colors_palette[palette] then
type = "linear",
colors_palette = "category10"
range = "width",
end
zero = false, -- do not include zero value
local palette_len, color_palette = cfg.colors_palette[palette][1],cfg.colors_palette[palette][2]
nice = true, -- force round numbers for y scale
local t = {}
___domain = { data = "chart", field = "x" }
local pos = 1
}
for i = 1, palette_len do
if xMin then xscale.domainMin = xMin end
t[i] = color_palette[pos]
if xMax then xscale.domainMax = xMax end
pos = pos + 1
if posxMin >or palette_lenxMax then posxscale.clamp = 1true end
if chartType == "rect" then
end
xscale.type = "ordinal"
--t = extend_table(palette, len or 1)
if not stacked then xscale.padding = 0.2 end -- pad each bar group
return t
else
if xType == "date" then xscale.type = "time"
elseif xType == "string" then xscale.type = "ordinal" end
end
 
return xscale
end
 
local function getYScale(chartType, stacked, yMin, yMax, yType)
-- ===================================================================================
if chartType == "pie" then return end
-- Wrap the graph inside a div structure and add an optional legend extenal to the
 
-- graph tag
local yscale =
-- ===================================================================================
{
local function wrap_graph(graph, legend, align, width)
name = "y",
local html = mw.html.create('div'):addClass('thumb')
type = "linear",
if align then
range = "height",
html:addClass('t' .. align)
-- area charts have the lower boundary of their filling at y=0 (see marks.properties.enter.y2), therefore these need to start at zero
else
zero = chartType ~= "line",
html:css('display', 'inline-block')
nice = true
end
}
if yMin then yscale.domainMin = yMin end
if yMax then yscale.domainMax = yMax end
if yMin or yMax then yscale.clamp = true end
if yType == "date" then yscale.type = "time"
elseif yType == "string" then yscale.type = "ordinal" end
if stacked then
yscale.___domain = { data = "stats", field = "sum_y" }
else
yscale.___domain = { data = "chart", field = "y" }
end
 
return yscale
html:tag('div')
:addClass('thumbinner')
:tag('div')
:wikitext(graph)
:done()
:tag('div')
:node(legend)
:css('width', tostring(width) .. 'px')
return tostring(html)
end
 
local function getColorScale(colors, chartType, xCount, yCount)
-- ===================================================================================
if not colors then
-- Build a legend item joining a color box with text
if (chartType == "pie" and xCount > 10) or yCount > 10 then colors = "category20" else colors = "category10" end
-- ===================================================================================
end
local function legend_item(color, text)
 
local item = mw.html.create('p'):cssText('margin:0px;font-size:100%;text-align:left')
local colorScale =
item:tag('span'):cssText(string.format('border:none;background-color:%s;color:%s;', color, color)):wikitext("██")
{
item:wikitext(string.format("&nbsp;%s", text))
name = "color",
return item
type = "ordinal",
range = colors,
___domain = { data = "chart", field = "series" }
}
if chartType == "pie" then colorScale.___domain.field = "x" end
return colorScale
end
 
local function getAlphaColorScale(colors, y)
-- ===================================================================================
local alphaScale
-- Build a legend
-- if there is at least one color in the format "#aarrggbb", create a transparency (alpha) scale
-- ===================================================================================
if isTable(colors) then
local function build_legend(colors, labels, title, ncols)
local alphas = {}
local legend = mw.html.create('div'):addClass('thumbcaption'):css('text-align', 'center')
local hasAlpha = false
legend:wikitext(title or '')
for i = 1, #colors do
local legend_list= mw.html.create('div')
local a, rgb = string.match(colors[i], "#(%x%x)(%x%x%x%x%x%x)")
local cols = tonumber(ncols or "1")
if cols>1a then
hasAlpha = true
local col_string = tostring(cols)
alphas[i] = tostring(tonumber(a, 16) / 255.0)
legend_list
colors[i] = "#" .. rgb
:css('-moz-column-count', col_string)
else
:css('-webkit-column-count', col_string)
alphas[i] = "1"
:css('column-count:', col_string)
end
end
if not isTable(colors) then
for i = #colors + 1, #y do alphas[i] = "1" end
colors = generate_color_palette(colors, #labels)
if hasAlpha then alphaScale = { name = "transparency", type = "ordinal", range = alphas } end
end
end
for i,label in ipairs(labels) do
return alphaScale
legend_list:node(legend_item(colors[i], label))
end
legend:node(legend_list)
return legend
end
 
local function getValueScale(fieldName, min, max, type)
-- ===================================================================================
local valueScale =
-- Return the json code to build a pie chart
{
-- ===================================================================================
name = fieldName,
function p.pie_chart_json(args)
type = type or "linear",
local data = {}
___domain = { data = "chart", field = fieldName },
for pos,x in ipairs(args.values) do
range = { min, max }
data[pos] = { x = x, color = args.colors[pos] }
}
end
return valueScale
local graph = {
version = 1,
name = args.name,
width = math.floor(args.graphwidth / 3),
height = math.floor(args.graphwidth / 3),
data = {
{
name = "table",
values = data,
transform = { { type = "pie", value = "data.x" } }
}
},
marks = {
{
type = "arc",
from = { data = "table"},
properties = {
enter = {
x = { field = "data.x", group = "width", mult = 0.5 },
y = { field = "data.x", group = "height", mult = 0.5 },
startAngle = { field = "startAngle"},
endAngle = {field = "endAngle"},
innerRadius = {value = args.inner_radius},
outerRadius = {value = args.outer_radius },
stroke = {value = "#fff"},
},
update = { fill = { field = "data.color"} },
hover = { fill = {value = "pink"} }
},
}
}
}
local flags = return_yes_value(args[cfg.localization.debug_json]) and mw.text.JSON_PRETTY
return mw.text.jsonEncode(graph, flags)
end
 
local function addInteractionToChartVisualisation(plotMarks, colorField, dataField)
-- ===================================================================================
-- initial setup
-- Interface function for template:pie_chart
if not plotMarks.properties.enter then plotMarks.properties.enter = {} end
-- ===================================================================================
plotMarks.properties.enter[colorField] = { scale = "color", field = dataField }
function p.pie_chart(frame)
 
local args = getArgs(frame, {parentOnly = true})
-- action when cursor is over plot mark: highlight
local arguments = { }
if not plotMarks.properties.hover then plotMarks.properties.hover = {} end
arguments.name = args[cfg.localization.name] or 'grafico a torta'
plotMarks.properties.hover[colorField] = { value = "red" }
arguments.values = numericArray(args[cfg.localization.values], 0)
 
-- get marks colors, use default category10 palette as default,
-- action when cursor leaves plot mark: reset to initial setup
-- if colors is not the name of a palette then read it as an array of colors
if not plotMarks.properties.update then plotMarks.properties.update = {} end
arguments.colors = args[cfg.localization.colors] or "category10"
plotMarks.properties.update[colorField] = { scale = "color", field = dataField }
if not cfg.colors_palette[arguments.colors] then
arguments.colors = stringArray(arguments.colors)
else
arguments.colors = generate_color_palette(arguments.colors)
end
arguments.labels = {}
local index = 1
label_string = cfg.localization.label
if args[label_string] then
arguments.labels[1] = args[label_string]
index = 2
end
while true do
if not args[label_string .. tostring(index)] then break end
arguments.labels[index] = args[label_string .. tostring(index)]
index = index + 1
end
-- Se è definito 'other' assumo che sia calcolato su base %, calcolo il suo valore e l'aggiungo alla tabella dati
if args[cfg.localization.other] then
local total = 0
for _,val in ipairs(arguments.values) do total = total + val end
if total > 0 and total < 100 then
arguments.values[#arguments.values+1]= math.max(0, 100 - total)
arguments.labels[#arguments.values] = "Altri"
end
end
arguments.colors = extend_table(arguments.colors, #arguments.values)
arguments.graphwidth = tonumber(args[cfg.localization.width]) or cfg.default.width_piechart
arguments.outer_radius = arguments.graphwidth / 2 - 5
if return_yes_value(args[cfg.localization.ring]) then
arguments.inner_radius = arguments.outer_radius / 3
else
arguments.inner_radius = 0
end
arguments.legend = args[cfg.localization.internal_legend] or args[cfg.localization.external_legend] or 'Legenda'
for pos,txt in ipairs(arguments.labels) do
arguments.labels[pos] = txt .. ' (' .. mw.language.getContentLanguage():formatNum(arguments.values[pos] or 0) .. '%)'
end
local json_code = p.pie_chart_json(arguments)
if args[cfg.localization.debug_json] then return frame:extensionTag('syntaxhighlight', json_code) end
local external_legend
if not return_no_value(arguments.legend) then
external_legend = build_legend(arguments.colors, arguments.labels, arguments.legend, args[cfg.localization.nCols])
end
local chart = frame:extensionTag('graph', json_code)
local align = args[cfg.localization.thumb]
return wrap_graph(chart, external_legend, align, arguments.graphwidth ) .. errors_output(args.NoTracking)
end
 
local function getPieChartVisualisation(yCount, innerRadius, outerRadius, linewidth, radiusScale)
-- ===================================================================================
local chartvis =
-- Generate data structure for x and y axes
{
-- ===================================================================================
type = "arc",
local function build_ax(args, ax_name)
from = { data = "chart", transform = { { field = "y", type = "pie" } } },
 
properties =
{
enter = {
innerRadius = { value = innerRadius },
outerRadius = { },
startAngle = { field = "layout_start" },
endAngle = { field = "layout_end" },
stroke = { value = "white" },
strokeWidth = { value = linewidth or 1 }
}
}
}
if radiusScale then
chartvis.properties.enter.outerRadius.scale = radiusScale.name
chartvis.properties.enter.outerRadius.field = radiusScale.___domain.field
else
chartvis.properties.enter.outerRadius.value = outerRadius
end
 
addInteractionToChartVisualisation(chartvis, "fill", "x")
 
return chartvis
local ax = {
type = ax_name,
scale = ax_name,
title = args[ax_name .. 'title'],
format = args[ax_name .. 'format'],
grid = args[ax_name .. 'grid'],
layer = "back"
}
if isTable(args[ax_name .. 'AxisPrimaryTicks']) then
ax.values = args[ax_name .. 'AxisPrimaryTicks']
elseif args[ax_name .. 'nTicks'] then
ax.ticks = args[ax_name .. 'nTicks']
end
if args[ax_name .. 'SecondaryTicks'] then ax.subdivide = args[ax_name .. 'SecondaryTicks'] end
return ax
end
 
local function getChartVisualisation(chartType, stacked, colorField, yCount, innerRadius, outerRadius, linewidth, alphaScale, radiusScale, interpolate)
-- ===================================================================================
if chartType == "pie" then return getPieChartVisualisation(yCount, innerRadius, outerRadius, linewidth, radiusScale) end
-- Return a json structure to generate a a line/area/bar chart
-- Imported and modified from en:Module:Chart revision 670068988 of 5 july 2015
-- ===================================================================================
function p.chart_json(args)
-- build axes
local x_ax = build_ax(args, 'x')
local y_ax = build_ax(args, 'y')
local axes = { x_ax, y_ax }
 
local chartvis =
-- create data tuples, consisting of series index, x value, y value
{
local data = { name = "chart", values = {} }
type = chartType,
for i, yserie in ipairs(args.y) do
properties =
for j = 1, math.min(#yserie, #args.x) do
{
if yserie[j] ~= 'x' then data.values[#data.values + 1] = { series = args.seriesTitles[i], x = args.x[j], y = yserie[j] } end
-- chart creation event handler
end
enter =
end
{
-- calculate statistics of data as stacking requires cumulative y values
x = { scale = "x", field = "x" },
local stats
y = { scale = "y", field = "y" }
if args.is_stacked then
}
stats =
}
{
}
name = "stats", source = "chart", transform =
addInteractionToChartVisualisation(chartvis, colorField, "series")
{
if colorField == "stroke" then
{ type = "facet", keys = { "data.x" } },
chartvis.properties.enter.strokeWidth = { value = linewidth or 2.5 }
{ type = "stats", value = "data.y" }
end
}
}
end
-- create scales
local xscale =
{
name = "x",
type = "linear",
range = "width",
zero = false, -- do not include zero value
nice = true, -- force round numbers for y scale
___domain = { data = "chart", field = "data.x" }
}
if args.xMin then xscale.domainMin = args.xMin end
if args.xMax then xscale.domainMax = args.xMax end
if args.xMin or args.xMax then xscale.clamp = true end
if args.graph_type == "rect" or args.force_x_ordinal then xscale.type = "ordinal" end
 
if interpolate then chartvis.properties.enter.interpolate = { value = interpolate } end
local yscale =
{
name = "y",
type = "linear",
range = "height",
-- area charts have the lower boundary of their filling at y=0 (see marks.properties.enter.y2), therefore these need to start at zero
zero = args.graph_type ~= "line",
nice = true
}
if args.yMin then yscale.domainMin = args.yMin end
if args.yMax then yscale.domainMax = args.yMax end
if args.yMin or args.yMax then yscale.clamp = true end
if args.is_stacked then
yscale.___domain = { data = "stats", field = "sum" }
else
yscale.___domain = { data = "chart", field = "data.y" }
end
-- Color scale
local colorScale = { name = "color", type = "ordinal", range = args.colors }
local alphaScale
if args.alphas then alphaScale = { name = "transparency", graph_type = "ordinal", range = args.alphas } end
-- Symbols scale
local symbolsScale
if args.symbols then symbolsScale = { name = "symbols", type = "ordinal", range = args.symbols } end
-- for bar charts with multiple series: each series is grouped by the x value, therefore the series need their own scale within each x group
local groupScale
if args.graph_type == "rect" and not args.is_stacked and #args.y > 1 then
groupScale = { name = "series", type = "ordinal", range = "width", ___domain = { field = "data.series" } }
xscale.padding = 0.2 -- pad each bar group
end
 
if alphaScale then chartvis.properties.update[colorField .. "Opacity"] = { scale = "transparency" } end
-- decide if lines (strokes) or areas (fills) should be drawn
-- for bars and area charts set the lower bound of their areas
local colorField
if args.graph_typechartType == "linerect" thenor colorFieldchartType = "stroke" else colorField = "fillarea" endthen
if stacked then
-- for stacked charts this lower bound is the end of the last stacking element
chartvis.properties.enter.y2 = { scale = "y", field = "layout_end" }
else
--[[
for non-stacking charts the lower bound is y=0
TODO: "yscale.zero" is currently set to "true" for this case, but "false" for all other cases.
For the similar behavior "y2" should actually be set to where y axis crosses the x axis,
if there are only positive or negative values in the data ]]
chartvis.properties.enter.y2 = { scale = "y", value = 0 }
end
end
-- for bar charts ...
if chartType == "rect" then
-- set 1 pixel width between the bars
chartvis.properties.enter.width = { scale = "x", band = true, offset = -1 }
-- for multiple series the bar marking needs to use the "inner" series scale, whereas the "outer" x scale is used by the grouping
if not stacked and yCount > 1 then
chartvis.properties.enter.x.scale = "series"
chartvis.properties.enter.x.field = "series"
chartvis.properties.enter.width.scale = "series"
end
end
-- stacked charts have their own (stacked) y values
if stacked then chartvis.properties.enter.y.field = "layout_start" end
 
-- if there are multiple series group these together
-- create chart markings
if yCount == 1 then
local marks =
chartvis.from = { data = "chart" }
{
else
type = args.graph_type,
-- if there are multiple series, connect colors to series
properties =
chartvis.properties.update[colorField].field = "series"
{
if alphaScale then chartvis.properties.update[colorField .. "Opacity"].field = "series" end
-- chart creation event handler
-- apply a grouping (facetting) transformation
enter =
chartvis =
{
{
x = { scale = "x", field = "data.x" },
type = "group",
y = { scale = "y", field = "data.y" },
marks = { chartvis },
from =
{
data = "chart",
transform =
{
{
type = "facet",
groupby = { "series" }
}
}
}
}
-- for stacked charts apply a stacking transformation
if stacked then
table.insert(chartvis.from.transform, 1, { type = "stack", groupby = { "x" }, sortby = { "series" }, field = "y" } )
else
-- for bar charts the series are side-by-side grouped by x
if chartType == "rect" then
-- for bar charts with multiple series: each serie is grouped by the x value, therefore the series need their own scale within each x group
local groupScale =
{
name = "series",
type = "ordinal",
range = "width",
___domain = { field = "series" }
}
 
chartvis.from.transform[1].groupby = "x"
},
chartvis.scales = { groupScale }
-- chart update event handler
chartvis.properties = { enter = { x = { field = "key", scale = "x" }, width = { scale = "x", band = true } } }
update = { },
end
-- chart hover event handler
end
hover = { }
end
}
}
marks.properties.update[colorField] = { scale = "color" }
marks.properties.hover[colorField] = { value = "red" }
if alphaScale then marks.properties.update[colorField .. "Opacity"] = { scale = "transparency" } end
-- for bars and area charts set the lower bound of their areas
if args.graph_type == "rect" or args.graph_type == "area" then
if args.is_stacked then
-- for stacked charts this lower bound is cumulative/stacking
marks.properties.enter.y2 = { scale = "y", field = "y2" }
else
--[[
for non-stacking charts the lower bound is y=0
TODO: "yscale.zero" is currently set to "true" for this case, but "false" for all other cases.
For the similar behavior "y2" should actually be set to where y axis crosses the x axis,
if there are only positive or negative values in the data ]]
marks.properties.enter.y2 = { scale = "y", value = 0 }
end
end
-- for bar charts ...
if args.graph_type == "rect" then
-- set 1 pixel width between the bars
marks.properties.enter.width = { scale = "x", band = true, offset = -1 }
-- for multiple series the bar marking need to use the "inner" series scale, whereas the "outer" x scale is used by the grouping
if not args.is_stacked and #args.y > 1 then
marks.properties.enter.x.scale = "series"
marks.properties.enter.x.field = "data.series"
marks.properties.enter.width.scale = "series"
end
end
if args.graph_type == "line" then marks.properties.enter.strokeWidth = { value = args.stroke_thickness } end
-- stacked charts have their own (stacked) y values
if args.is_stacked then marks.properties.enter.y.field = "y" end
-- set interpolation mode
if args.interpolate then marks.properties.enter.interpolate = { value = args.interpolate } end
local symbolsMarks
if symbolsScale then
symbolsMarks = {
type = "symbol",
from = { data = "chart" },
properties = {
enter =
{
x = { scale = "x", field = "data.x" },
y = { scale = "y", field = "data.y" },
shape = { scale = "symbols" },
},
update = { stroke = { scale = "color"} }
}
}
if args.symbol_size then symbolsMarks.properties.enter.size = { value = args.symbol_size } end
end
if #args.y == 1 then
marks.from = { data = "chart" }
marks = { marks, symbolsMarks }
else
-- if there are multiple series, connect colors to series
if args.graph_type == "rect" and args.colorsByGroup then
marks.properties.update[colorField].field = "data.x"
else
marks.properties.update[colorField].field = "data.series"
end
if symbolsScale then
symbolsMarks.properties.enter.shape.field = "data.series"
symbolsMarks.properties.update.stroke.field = "data.series"
end
if alphaScale then marks.properties.update[colorField .. "Opacity"].field = "data.series" end
 
return chartvis
-- apply a grouping (facetting) transformation
end
marks =
{
type = "group",
marks = { marks, symbolsMarks },
from =
{
data = "chart",
transform =
{
{
type = "facet",
keys = { "data.series" }
}
}
}
}
-- for stacked charts apply a stacking transformation
if args.is_stacked then
marks.from.transform[2] = { type = "stack", point = "data.x", height = "data.y" }
else
-- for bar charts the series are side-by-side grouped by x
if args.graph_type == "rect" then
marks.from.transform[1].keys = "data.x"
marks.scales = { groupScale }
marks.properties = { enter = { x = { field = "key", scale = "x" }, width = { scale = "x", band = true } } }
end
end
marks = { marks }
end
 
local function getTextMarks(chartType, outerRadius, radiusScale)
-- create legend
local legendtextmarks
if chartType == "pie" then
if args.internal_legend then
textmarks =
legend = { { fill = "color", stroke = "color", title = args.internal_legend } }
{
end
type = "text",
from = { data = "chart", transform = { { field = "y", type = "pie" } } },
properties =
{
enter =
{
x = { group = "width", mult = 0.5 },
y = { group = "height", mult = 0.5 },
radius = { offset = -4 },
theta = { field = "layout_mid" },
fill = { value = "white" },
align = { value = "center" },
baseline = { value = "top" },
text = { field = "y" },
angle = { field = "layout_mid", mult = 180.0 / math.pi },
fontSize = { value = math.ceil(outerRadius / 10) }
}
}
}
if radiusScale then
textmarks.properties.enter.radius.scale = radiusScale.name
textmarks.properties.enter.radius.field = radiusScale.___domain.field
else
textmarks.properties.enter.radius.value = outerRadius
end
end
return textmarks
end
 
local function getAxes(xTitle, xFormat, xType, yTitle, yFormat, yType, chartType)
-- build final output object
local xAxis, yAxis
local scales = { xscale, yscale, colorScale}
if chartType ~= "pie" then
if alphaScale then scales[#scales+1] = alphaScale end
if xType == "integer" ifand not symbolsScalexFormat then scales[#scales+1]xFormat = symbolsScale"d" end
xAxis =
local output =
{
{
version type = 1"x",
scale = "x",
width = args.graphwidth,
title = xTitle,
height = args.graphheight,
format = xFormat
data = { data, stats },
}
scales = scales,
 
axes = axes,
if yType == "integer" and not yFormat then yFormat = "d" end
marks = marks ,
yAxis =
legends = legend
{
}
type = "y",
local flags = return_yes_value(args[cfg.localization.debug_json]) and mw.text.JSON_PRETTY
scale = "y",
return mw.text.jsonEncode(output, flags)
title = yTitle,
format = yFormat
}
end
 
return xAxis, yAxis
end
 
local function getLegend(legendTitle, chartType, outerRadius)
local legend =
{
fill = "color",
stroke = "color",
title = legendTitle,
}
if chartType == "pie" then
-- move legend from center position to top
legend.properties = { legend = { y = { value = -outerRadius } } }
end
return legend
end
 
-- ===================================================================================
-- Interface function for template:Grafico a linee
-- ===================================================================================
function p.chart(frame)
-- chart width and height
local graphwidth = tonumber(frame.args.width) or 200
local graphheight = tonumber(frame.args.height) or 200
-- chart type
local chartType = frame.args.type or "line"
-- interpolation mode for line and area charts: linear, step-before, step-after, basis, basis-open, basis-closed (type=line only), bundle (type=line only), cardinal, cardinal-open, cardinal-closed (type=line only), monotone
local interpolate = frame.args.interpolate
-- mark colors (if no colors are given, the default 10 color palette is used)
local colors = stringArray(frame.args.colors)
-- for line charts, the thickness of the line; for pie charts the gap between each slice
local linewidth = tonumber(frame.args.linewidth)
-- x and y axis caption
local xTitle = frame.args.xAxisTitle
local yTitle = frame.args.yAxisTitle
-- x and y value types
local xType = frame.args.xType
local yType = frame.args.yType
-- override x and y axis minimum and maximum
local xMin = frame.args.xAxisMin
local xMax = frame.args.xAxisMax
local yMin = frame.args.yAxisMin
local yMax = frame.args.yAxisMax
-- override x and y axis label formatting
local xFormat = frame.args.xAxisFormat
local yFormat = frame.args.yAxisFormat
-- show legend with given title
local legendTitle = frame.args.legend
-- show values as text
local showValues = frame.args.showValues
-- pie chart radiuses
local innerRadius = tonumber(frame.args.innerRadius) or 0
local outerRadius = math.min(graphwidth, graphheight)
-- format JSON output
local formatJson = frame.args.formatjson
 
-- Readget axx argumentsvalues
local x
local function read_ax_arguments(args, ax_name, arguments)
x, xType, xMin, xMax = deserializeXData(frame.args.x, xType, xMin, xMax)
arguments[ax_name .. 'title'] = args[cfg.localization[ax_name .. 'AxisTitle']]
arguments[ax_name .. 'format'] = args[cfg.localization[ax_name .. 'AxisFormat']]
local grid = cfg.default[ax_name .. 'Grid']
if grid then
grid = not return_no_value(args[cfg.localization[ax_name .. 'Grid']])
else
grid = return_yes_value(args[cfg.localization[ax_name .. 'Grid']])
end
arguments[ax_name .. 'grid'] = grid
arguments[ax_name .. 'AxisPrimaryTicks'] = numericArray(args[cfg.localization[ax_name .. 'AxisPrimaryTicks']])
arguments[ax_name.. 'nTicks'] = tonumber(args[cfg.localization[ax_name .. 'AxisPrimaryTicksNumber']])
arguments[ax_name .. 'SecondaryTicks'] = tonumber(args[cfg.localization[ax_name .. 'AxisSecondaryTicks']])
arguments[ax_name ..'Min'] = tonumber(args[cfg.localization[ax_name .. 'AxisMin']])
arguments[ax_name ..'Max'] = tonumber(args[cfg.localization[ax_name .. 'AxisMax']])
end
 
-- get graphy values type(series)
local yValues = {}
local function get_graph_type(graph_string)
local seriesTitles = {}
if graph_string == nil then return "line", false end
for name, value in pairs(frame.args) do
local graph_type = cfg.graph_type[mw.ustring.lower(graph_string)]
local yNum
if graph_type then return graph_type[1], graph_type[2] end
if name == "y" then yNum = 1 else yNum = tonumber(string.match(name, "^y(%d+)$")) end
add_error('type_unknown', {graph_string})
if yNum then
end
yValues[yNum] = value
-- name the series: default is "y<number>". Can be overwritten using the "y<number>Title" parameters.
seriesTitles[yNum] = frame.args["y" .. yNum .. "Title"] or name
end
end
local y
y, yType, yMin, yMax = deserializeYData(yValues, yType, yMin, yMax)
 
-- create data tuples, consisting of series index, x value, y value
local data
if chartType == "pie" then
-- for pie charts the second second series is merged into the first series as radius values
data = convertXYToSingleSeries(x, y, xType, yType, { "y", "r" })
else
data = convertXYToManySeries(x, y, xType, yType, seriesTitles)
end
 
-- configure stacked charts
local stacked = false
local stats
if string.sub(chartType, 1, 7) == "stacked" then
chartType = string.sub(chartType, 8)
if #y > 1 then -- ignore stacked charts if there is only one series
stacked = true
-- aggregate data by cumulative y values
stats =
{
name = "stats", source = "chart", transform =
{
{
type = "aggregate",
groupby = { "x" },
summarize = { y = "sum" }
}
}
}
end
end
 
-- create scales
local scales = {}
 
local xscale = getXScale(chartType, stacked, xMin, xMax, xType)
table.insert(scales, xscale)
local yscale = getYScale(chartType, stacked, yMin, yMax, yType)
table.insert(scales, yscale)
 
 
local colorScale = getColorScale(colors, chartType, #x, #y)
table.insert(scales, colorScale)
 
local alphaScale = getAlphaColorScale(colors, y)
table.insert(scales, alphaScale)
 
local radiusScale
if chartType == "pie" and #y > 1 then
radiusScale = getValueScale("r", 0, outerRadius)
table.insert(scales, radiusScale)
end
 
-- decide if lines (strokes) or areas (fills) should be drawn
local colorField
if chartType == "line" then colorField = "stroke" else colorField = "fill" end
 
-- create chart markings
local chartvis = getChartVisualisation(chartType, stacked, colorField, #y, innerRadius, outerRadius, linewidth, alphaScale, radiusScale, interpolate)
 
-- text marks
local textmarks
if showValues then textmarks = getTextMarks(chartType, outerRadius, radiusScale) end
 
-- axes
local xAxis, yAxis = getAxes(xTitle, xFormat, xType, yTitle, yFormat, yType, chartType)
 
-- legend
local legend
if legendTitle then legend = getLegend(legendTitle, chartType, outerRadius) end
 
-- construct final output object
local output =
{
version = 2,
width = graphwidth,
height = graphheight,
data = { data, stats },
scales = scales,
axes = { xAxis, yAxis },
marks = { chartvis, textmarks },
legends = { legend }
}
 
local flags
if formatJson then flags = mw.text.JSON_PRETTY end
return mw.text.jsonEncode(output, flags)
end
 
function p.mapWrapper(frame)
return p.map(frame:getParent())
end
 
function p.chartWrapper(frame)
local args = getArgs(frame, {parentOnly = true})
return p.chart(frame:getParent())
-- analyze and build data to build the chart
local arguments = { }
arguments.graphwidth = tonumber(args[cfg.localization.width]) or cfg.default.width
arguments.graphheight = tonumber(args[cfg.localization.height]) or cfg.default.height
arguments.graph_type, arguments.is_stacked = get_graph_type(args[cfg.localization.type])
arguments.interpolate = args[cfg.localization.interpolate]
if arguments.interpolate and not cfg.interpolate[arguments.interpolate] then
add_error('value_not_valid', {cfg.localization.interpolate, arguments.interpolate})
interpolate = nil
end
-- get marks symbols, default symbol is used if the type of graph is line, otherwise the default
-- is not to use symbol.
if arguments.graph_type == "line" and not return_no_value(args[cfg.localization.symbols]) then
arguments.symbols = stringArray(args[cfg.localization.symbols]) or cfg.default.symbol
arguments.symbol_size = tonumber(args[cfg.localization.symbolSize]) or cfg.default.symbol_size
end
if arguments.graph_type =="line" then
arguments.stroke_thickness = tonumber(args[cfg.localization.strokeThickness]) or cfg.default.stroke_thickness
end
-- show legend, optionally caption
arguments.internal_legend = args[cfg.localization.internal_legend]
-- get x values
arguments.x = numericArray(args.x)
arguments.force_x_ordinal = false
if #arguments.x == 0 then
arguments.force_x_ordinal = true
else
for _,val in ipairs(arguments.x) do
if val == 'x' then
arguments.force_x_ordinal = true
break
end
end
end
if arguments.force_x_ordinal then arguments.x = stringArray(args.x) end
-- get y values (series)
arguments.y = {}
local index = 1
arguments.seriesTitles = {}
if args.y then
arguments.y[1] = numericArray(args.y)
arguments.seriesTitles[1] = args[string.gsub(cfg.localization.yTitle, '#', '')] or args[string.gsub(cfg.localization.yTitle, '#', '1')] or "y"
index = 2
end
while true do
if not args['y'..tostring(index)] then break end
arguments.y[index] = numericArray(args['y'..tostring(index)])
arguments.seriesTitles[index] = args[string.gsub(cfg.localization.yTitle, '#', tostring(index))] or ('y' .. tostring(index))
index = index + 1
end
-- ignore stacked charts if there is only one series
if #arguments.y == 1 then arguments.is_stacked = false end
-- read axes arguments
read_ax_arguments(args, 'x', arguments)
read_ax_arguments(args, 'y', arguments)
-- get marks colors, default palette is category10,
-- if colors is not the name of a predefined palette then read it as an array of colors
arguments.colors = args[cfg.localization.colors] or "category10"
if not cfg.colors_palette[arguments.colors] then
arguments.colors = stringArray(arguments.colors)
elseif arguments.colors ~="category10" and arguments.colors ~="category20" then
arguments.colors = generate_color_palette(arguments.colors)
end
-- assure that colors, stroke_thickness and symbols table are at least the same lenght that the number of
-- y series
if isTable(arguments.colors) then arguments.colors = extend_table(arguments.colors, #arguments.y) end
if isTable(arguments.stroke_thickness) then arguments.stroke_thickness = extend_table(arguments.stroke_thickness, #arguments.y) end
if isTable(arguments.symbols) then arguments.symbols = extend_table(arguments.symbols, #arguments.y) end
-- if there is at least one color in the format "#aarrggbb", create a transparency (alpha) scale
if isTable(arguments.colors) then
alphas = {}
local hasAlpha = false
for i, color in ipairs(arguments.colors) do
local a, rgb = string.match(color, "#(%x%x)(%x%x%x%x%x%x)")
if a then
hasAlpha = true
alphas[i] = tostring(tonumber(a, 16) / 255.0)
arguments.colors[i] = "#" .. rgb
else
alphas[i] = "1"
end
end
for i = #arguments.colors + 1, #arguments.y do alphas[i] = "1" end
if hasAlpha then arguments.alphas = alphas end
elseif args[cfg.localization.alpha] then
arguments.alphas = stringArray(args[cfg.localization.alpha])
if arguments.alphas then
for i,a in ipairs(arguments.alphas) do arguments.alphas[i] = tostring(tonumber(a, 16) / 255.0) end
arguments.alphas = extend_table(arguments.alphas, #arguments.y)
end
end
arguments.colorsByGroup = return_yes_value(args[cfg.localization.colorsByGroup])
local chart_json = p.chart_json(arguments)
if args[cfg.localization.debug_json] then return frame:extensionTag('syntaxhighlight', chart_json) end
local external_legend
if args[cfg.localization.external_legend] then
external_legend = build_legend(arguments.colors, arguments.seriesTitles, args[cfg.localization.external_legend],
args[cfg.localization.nCols])
end
local chart = frame:extensionTag('graph', chart_json)
local align = args[cfg.localization.thumb]
return wrap_graph(chart, external_legend, align, arguments.graphwidth) .. errors_output(args.NoTracking)
end