Modulo:Graph: differenze tra le versioni
Contenuto cancellato Contenuto aggiunto
Revet back the change due to current Pie chart syntax error Etichetta: Ripristino manuale |
Upgrade syntax to Vega 2.0 (This version should work) |
||
Riga 1:
local p = {}
local cfg = mw.loadData( 'Module:Graph/sandbox/Configurazione' );
local getArgs = require('Module:Arguments').getArgs
local errors = { }
Riga 9:
table.insert(t, s)
end
end
Line 50 ⟶ 39:
end
-- ==============================================================================
-- Return true if t is a table
-- ===============================================================================
local function isTable(t)
return type(t) == "table"
end
-- ===============================================================================
-- Class to manage access to arguments
-- ===============================================================================
local Args = {}
Args.__index = Args
function Args.new(arguments)
local self = {}
self.args = arguments
return setmetatable(self, Args)
end
-- ===============================================================================
-- Return value of parameter name
-- ===============================================================================
function Args:value(name, default, transform)
if cfg.localization[name] then
val = self.args[cfg.localization[name]]
if val and transform then
val = transform(val)
end
if val then
return val
end
return default
end
return --TODO raise an error ?
end
-- ===============================================================================
-- Return value of parameter name as number
-- ===============================================================================
function Args:number(name, default)
local val = self:value(name)
return (val and tonumber(val)) or default
end
-- ===============================================================================
-- Return array of value of parameters base_name, base_name2, ... base_namen
-- ===============================================================================
function Args:values_indexed(base_name)
local base_name_localized = cfg.localization[base_name]
if not base_name_localized then return end
local values = {}
local index = 1
if self.args[base_name_localized] then
values[1] = self.args[base_name_localized]
index = 2
end
while true do
local val = self.args[base_name_localized .. tostring(index)]
if not val then break end
values[index] = val
index = index + 1
end
return values
end
-- ===============================================================================
-- Return true if parameter arg is present and is a yes value (a valor
-- in the array cfg.yes_values
-- ===============================================================================
function Args:is_yes(name)
local val = self:value(name)
return val and cfg.yes_values[mw.ustring.lower(val)]
end
-- ===============================================================================
-- Return true if parameter arg is present and is a yes value (a valor
-- in the array cfg.yes_values
-- ===============================================================================
function Args:is_no(name)
local val = self:value(name)
return val and cfg.no_values[mw.ustring.lower(val)]
end
setmetatable(Args, { __call = function(_, ...) return Args.new(...) end })
-- ===============================================================================
Line 106 ⟶ 167:
end
-- ==============================================================================
Line 130 ⟶ 184:
-- ==============================================================================
-- Generate a color palette from
-- or an array of color values
-- ==============================================================================
local function generate_color_palette(palette,
local color_palette = {}
local palette_len
palette = palette or "category10"
if isTable(palette) and #palette == 1 and cfg.colors_palette[palette[1]] then
palette_len, color_palette = cfg.colors_palette[palette[1]][1], cfg.colors_palette[palette[1]][2]
elseif not isTable(palette) then
palette = (cfg.colors_palette[palette] and palette) or "category10"
palette_len, color_palette = cfg.colors_palette[palette][1], cfg.colors_palette[palette][2]
else
palette_len, color_palette = #palette, palette
end
local new_len = new_len or palette_len
local t = {}
local pos = 1
for i = 1,
t[i] = color_palette[pos]
pos = pos + 1
if pos > palette_len then pos = 1 end
end
return t
end
Line 164 ⟶ 226:
:addClass('thumbinner')
:tag('div')
:wikitext(
:done()
:tag('div')
Line 196 ⟶ 258:
:css('-webkit-column-count', col_string)
:css('column-count:', col_string)
end
for i,label in ipairs(labels) do
Line 212 ⟶ 271:
function p.pie_chart_json(args)
local data = {}
for pos
data[pos] = { x =
end
local graph = {
version =
name = args.name,
width = math.floor(args.graphwidth / 3),
Line 224 ⟶ 283:
name = "table",
values = data,
transform = { { type = "pie", value = "
}
},
Line 230 ⟶ 289:
{
type = "arc",
from = { data = "table"
transform = { { field = "y", type = "pie"} }
},
properties = {
enter = {
innerRadius = {value = args.inner_radius},
startAngle = { field = "layout_start"},
outerRadius = {value = args.outer_radius },
endAngle = {field = "layout_end"},
stroke = {value = "#fff"},
fill = { field = "x", scale = "color"},
},
},
}
},
scales = {
{
name = "color",
range = args.colors,
___domain = { data = "table", field = "x"},
["type"] = "ordinal"
}
}
}
if args.internal_legend then
data[#data] = { { fill = "color", stroke = "color", title = args.internal_legend } }
end
local flags = args.debug_json and mw.text.JSON_PRETTY
return mw.text.jsonEncode(graph, flags)
end
Line 255 ⟶ 324:
-- ===================================================================================
function p.pie_chart(frame)
local args = Args(getArgs(frame, {parentOnly = true}))
local
-- Se non trova valori validi termina
if not pie_args.values or #pie_args.values == 0 then
add_error('no_values')
return errors_output(args.NoTracking)
end
pie_args.labels = args:values_indexed('label')
-- Se è definito 'other' assumo che sia calcolato su base %, calcolo il suo valore e l'aggiungo alla tabella dati
if args
local total = 0
for _,val in ipairs(
if total > 0 and total < 100 then
end
end
local palette = stringArray(args:value('colors'))
if not palette then palette = stringArray(args:value('color')) end
pie_args.colors = generate_color_palette(palette, #pie_args.values)
pie_args.graphwidth = args:number('width', cfg.default.width_piechart)
pie_args.outer_radius = pie_args.graphwidth / 2 - 5
if args:is_yes('ring') then
pie_args.inner_radius = pie_args.outer_radius / 3
else
end
for pos,txt in ipairs(
end
pie_args.debug_json = args:is_yes('debug_json')
local json_code = p.pie_chart_json(pie_args)
if pie_args.debug_json then return frame:extensionTag('syntaxhighlight', json_code) end
local external_legend
if not
external_legend = build_legend(
end
local chart = frame:extensionTag('graph', json_code)
local align = args
return wrap_graph(chart, external_legend, align,
end
Line 355 ⟶ 414:
stats =
{
name = "
{
{ type = "facet", keys = { "
{ type = "
}
}
Line 370 ⟶ 429:
zero = false, -- do not include zero value
nice = true, -- force round numbers for y scale
___domain = { data = "chart", field = "
}
if args.xMin then xscale.domainMin = args.xMin end
Line 390 ⟶ 449:
if args.yMin or args.yMax then yscale.clamp = true end
if args.is_stacked then
yscale.___domain = { data = "
else
yscale.___domain = { data = "chart", field = "
end
-- Color scale
Line 404 ⟶ 463:
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 = "
xscale.padding = 0.2 -- pad each bar group
end
Line 421 ⟶ 480:
enter =
{
x = { scale = "x", field = "
y = { scale = "y", field = "
},
Line 455 ⟶ 514:
if not args.is_stacked and #args.y > 1 then
marks.properties.enter.x.scale = "series"
marks.properties.enter.x.field = "
marks.properties.enter.width.scale = "series"
end
Line 472 ⟶ 531:
enter =
{
x = { scale = "x", field = "
y = { scale = "y", field = "
shape = { scale = "symbols" },
},
Line 487 ⟶ 546:
-- if there are multiple series, connect colors to series
if args.graph_type == "rect" and args.colorsByGroup then
marks.properties.update[colorField].field = "
else
marks.properties.update[colorField].field = "
end
if symbolsScale then
symbolsMarks.properties.enter.shape.field = "
symbolsMarks.properties.update.stroke.field = "
end
if alphaScale then marks.properties.update[colorField .. "Opacity"].field = "
-- apply a grouping (facetting) transformation
Line 509 ⟶ 568:
{
type = "facet",
keys = { "
}
}
Line 516 ⟶ 575:
-- for stacked charts apply a stacking transformation
if args.is_stacked then
marks.from.transform[2] = { type = "stack", point = "
else
-- for bar charts the series are side-by-side grouped by x
if args.graph_type == "rect" then
marks.from.transform[1].keys = "
marks.scales = { groupScale }
marks.properties = { enter = { x = { field = "key", scale = "x" }, width = { scale = "x", band = true } } }
Line 540 ⟶ 599:
local output =
{
version =
width = args.graphwidth,
height = args.graphheight,
Line 549 ⟶ 608:
legends = legend
}
local flags =
return mw.text.jsonEncode(output, flags)
end
Line 559 ⟶ 618:
-- Read ax arguments
local function read_ax_arguments(args, ax_name,
local grid = cfg.default[ax_name .. 'Grid']
if grid then
grid = not
else
grid =
end
end
Line 584 ⟶ 643:
end
local args = Args(getArgs(frame, {parentOnly = true}))
-- analyze and build data to build the chart
local
if
add_error('value_not_valid', {cfg.localization.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
end
if
end
-- show legend, optionally caption
-- get x values
if #
else
for _,val in ipairs(
if val == 'x' then
break
end
end
end
if
-- get y values (series)
chart_arg.y = args:values_indexed('y')
if not chart_arg.y then return '' end --TODO message error mancanza dati per asse y
for pos, y in ipairs(chart_arg.y) do
chart_arg.seriesTitles[pos] = chart_arg.seriesTitles[pos] or ("y" .. tostring(pos))
end
-- ignore stacked charts if there is only one series
if #
-- read axes arguments
read_ax_arguments(args, 'x',
read_ax_arguments(args, 'y',
-- 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
--if not cfg.colors_palette[
--
--elseif
--
--end
local palette = stringArray(args:value('colors'))
if not palette then palette = stringArray(args:value('color')) end
chart_arg.colors = generate_color_palette(palette, #chart_arg.y)
--if true then return mw.text.jsonEncode(chart_arg.colors) end
-- assure that colors, stroke_thickness and symbols table are at least the same lenght that the number of
-- y series
if isTable(
if isTable(
-- if there is at least one color in the format "#aarrggbb", create a transparency (alpha) scale
if isTable(
alphas = {}
local hasAlpha = false
for i, color in ipairs(
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)
else
alphas[i] = "1"
end
end
for i = #
if hasAlpha then
elseif args[cfg.localization.alpha] then
if
for i,a in ipairs(
end
end
chart_arg.debug_json = args:is_yes('debug_json') or false
-- if
local chart_json = p.chart_json(chart_arg)
if chart_arg.debug_json then return frame:extensionTag('syntaxhighlight', chart_json) end
local external_legend
if args
external_legend = build_legend(
args
end
local chart = frame:extensionTag('graph', chart_json)
local align = args[cfg.localization.thumb]
return wrap_graph(chart, external_legend, align,
end
-- ===================================================================================
-- Return a json structure to generate a map chart
-- Imported and modified from de:Modul:Graph revision 142970943 of 10 giugno 2015
-- ===================================================================================
function p.map_json(args)
-- create highlight scale
local scales
if args.isNumbers then
scales =
{
{
name = "color",
type = args.scaleType,
___domain = { data = "highlights", field = "v" },
range = args.colorScale,
nice = true
}
}
if args.domainMin then scales[1].domainMin = args.domainMin end
if args.domainMax then scales[1].domainMax = args.domainMax end
local exponent = string.match(args.scaleType, "pow%s+(%d+%.?%d+)") -- check for exponent
if exponent then
scales[1].type = "pow"
scales[1].exponent = args.exponent
end
end
-- create legend
if args.legend then
legend =
{
{
fill = "color",
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(args.basemap, 1, 7) == "http://") or (string.sub(args.basemap, 1, 8) == "https://") or (string.sub(args.basemap, 1, 2) == "//") then
basemapUrl = args.basemap
else
-- if not a (supported) url look for a colon as namespace separator. If none prepend default map directory name.
local basemap = args.basemap
if not string.find(basemap, ":") then basemap = cfg.default.base_map_directory .. 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 = args.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 = args.scale,
translate = { 0, 0 },
projection = args.projection
},
{
-- join ("zip") of mutiple data source: here map paths data and highlights
type = "zip",
key = "id", -- key for map paths data
with = "highlights", -- name of highlight data source
withKey = "id", -- key for highlight data source
as = "zipped", -- name of resulting table
default = { data = { v = args.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 = "path" } },
update = { fill = { field = "zipped.data.v" } },
hover = { fill = { value = "darkgrey" } }
}
}
},
legends = legend
}
if (scales) then
output.scales = scales
output.marks[1].properties.update.fill.scale = "color"
end
flags = args.debug_json and mw.text.JSON_PRETTY
return mw.text.jsonEncode(output, flags)
end
-- ===================================================================================
-- Interface function for template:Mappa a colori
-- ===================================================================================
function p.map(frame)
local args = Args(getArgs(frame, {parentOnly = true}))
map_args = {}
-- map path data for geographic objects
map_args.basemap = args:value('basemap', cfg.default.world_map)
-- scaling factor
map_args.scale = args:number('scale', cfg.default.scale)
-- map projection, see https://github.com/mbostock/d3/wiki/Geo-Projections
map_args.projection = args:value('projection', "equirectangular")
-- defaultValue for geographic objects without data
map_args.defaultValue = args:value('defaultValue')
map_args.scaleType = args:value('scaleType' , "linear")
-- minimaler Wertebereich (nur für numerische Daten)
map_args.domainMin = args:number('domainMin')
-- maximaler Wertebereich (nur für numerische Daten)
map_args.domainMax = args:number('domainMax')
-- Farbwerte der Farbskala (nur für numerische Daten)
local palette = stringArray(args:value('colors'))
if not palette then palette = stringArray(args:value('color')) end
map_args.colors = generate_color_palette(palette)
-- show legend
map_args.legend = args[cfg.localization.internal_legend]
-- 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
map_args.values = {}
local isNumbers = nil
for name, value in pairs(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
map_args.values[#arguments.values+1] = data
end
end
if not map_args.defaultValue then
if isNumbers then map_args.defaultValue = 0 else map_args.defaultValue = "silver" end
end
map_args.isNumbers = isNumbers
map_args.debug_json = args:is_yes('debug_json')
local output_json = p.map_json(map_args)
if map_args.debug_json then
return frame:extensionTag('syntaxhighlight', output_json)
end
return frame:extensionTag('graph', output_json)
end
function p.palette_list(frame)
local output = { '<table class="wikitable"><tr><th>Nome</th><th>Colori</th></tr>'}
local palette_name = {}
for name,colors in pairs(cfg.colors_palette) do
palette_name[#palette_name+1] = name
end
table.sort(palette_name)
for _,name in ipairs(palette_name) do
dump(output, '<tr><td>' .. name .. '</td><td>')
for _,color in ipairs(cfg.colors_palette[name][2]) do
dump(output, string.format('<span style="border:none;background-color:%s;color:%s;">██</span>', color, color))
end
dump(output, '</td></tr>')
end
dump(output, '</table>')
return table.concat(output)
end
|