وحدة:Chart
Module Chart exports two functions: bar chart and pie chart
- Note - Template:Graph:Chart is an alternative template, that may be more suitable for your use case.
Drawing Bar charts: "bar chart"
Parameters
| parameter name | what it does |
|---|---|
| delimiter | string to delimit multiple values when given. default to colon ( : ). normally you do not want to touch this, it's provided for the off-chance you'll want to use colon as part of one of the parameters. |
| width | number. if provided, must be at least 200. default: 500 |
| height | number. if provided, must be at least 200. default: 350 |
| group n | (where "n" is a number. use "group 1", "group 2" etc. for as many groups as there are in the graph) the values to be charted. see below. |
| tooltip n | tooltip to be associated with specific bar. If no tooltip for a specific bar is defined, and this bar has a link, then this link will be used as tooltip. Otherwise, the tooltip will be combined from the group name and the value, optionally with "units prefix" and "units suffix". |
| links n | links to articles to be associated with specific bar |
| stack | whether to stack the different groups on top of each other. do not specify to show bars side by side. Any non-empty value means "yes". To say "no", simply do not supply this parameter at all, or leave the value blank. |
| tooltip value accumulation | useful only with stack: when set to true, tooltip will show accumulated value of all blocks up to current one |
| colors | the colors used to denote the various groups. should have exactly as many values as # of groups. can be given as standard html-recognized color names, or using #xxx or #xxxxxx notation. |
| x legends | The legends for the X values. Wikicode, such as internal links or templates can be used. |
| hide group legends | if set to true, group legends will not be shown below chart. Any non-empty value means "yes". To say "no", simply do not supply this parameter at all, or leave the value blank. |
| scale per group | set to use separate Y- scale for each group. leave empty to use one scale for all groups. incompatible with "stack". Note that even if some of the scales are exactly the same, they will be drawn separately when this setting is on. Any non-empty value means "yes". To say "no", simply do not supply this parameter at all, or leave the value blank. |
| units prefix | used in tooltip. e.g., $, so values will show as "$500" instead of "500" in the tooltip |
| units suffix | ditto for units suffix. use, e.g. "Kg" so values will show as 88Kg instead of 88 in tooltip. underscore ("_") are replaced by spaces, to allow a space between the value and the suffix. |
| group names | names of different groups |
Examples
Basic
{{ #invoke:Chart | bar chart
| group 1 = 40 : 50 : 60 : 20
| group 2 = 20 : 60 : 12 : 44
| group 3 = 55 : 14 : 33 : 5
| links 1 = Apple : McCintosh : Golden delicious
| links 2 = Banana : Apricot : Peach
| links 3 = Orange : Pear : Bear
| tooltip 2 = tooltip 1 : tooltip 2 : tooltip 3 : tooltip 4
| colors = green : yellow : orange
| group names = Apple : Banana : Orange
| x legends = Before : During : After : Post mortem
}}
خطأ: الوظيفة "bar chart" غير موجودة.
Stacked
Here is the same graph, with more modest height and width, using "stack", and adding "units suffix" for good measure:
{{ #invoke:Chart | bar chart
| height = 250
| width = 300
| stack = 1
| group 1 = 40 : 50 : 60 : 20
| group 2 = 20 : 60 : 12 : 44
| group 3 = 55 : 14 : 33 : 5
| colors = green : yellow : orange
| group names = Apple : Banana : Orange
| units suffix = Kg
| x legends = Before : During : After : Post mortem
}}
خطأ: الوظيفة "bar chart" غير موجودة.
Scale per group
It is possible to show each of the groups using different scale and units:
{{ #invoke:Chart | bar chart
| width = 800
| group 1 = 1500000 : 2500000 : 3500000
| group 2 = 200 : 5000 : 45000
| group 3 = 2000 : 5000 : 20000
| colors = red : blue : green
| group names = People : Cars : Average car cost
| x legends = 1920 : 1965 : 2002
| tooltip 2 = : There is no good data for number of cars in 1965. we use 5,000 as best estimate
| units prefix = : : $
| scale per group = 1
}}
خطأ: الوظيفة "bar chart" غير موجودة.
Notice the "units prefix" field: we do not need prefix for the first 2 groups, so we use colons with no content. As whitespace is ignored, we could write "::$" instead of " : : $".
Also note the special tooltip for the "Cars" number for 1965.
Here is an example with large number of groups - mainly to test how it looks with large number of legends:
{{ #invoke:Chart | bar chart
| width = 800
| height = 550
| group 1 = 1:2:3:4:5:4:3:2:1
| group 2 = 1:2:3:4:5:4:3:2:1
| group 3 = 1:2:3:4:5:4:3:2:1
| group 4 = 1:2:3:4:5:4:3:2:1
| group 5 = 1:2:3:4:5:4:3:2:1
| group 6 = 1:2:3:4:5:4:3:2:1
| group 7 = 1:2:3:4:5:4:3:2:1
| group 8 = 1:2:3:4:5:4:3:2:1
| group 9 = 1:2:3:4:5:4:3:2:1
| group 10 = 1:2:3:4:5:4:3:2:1
| group 11 = 1:2:3:4:5:4:3:2:1
| group 12 = 1:2:3:4:5:4:3:2:1
| group 13 = 1:2:3:4:5:4:3:2:1
| group 14 = 1:2:3:4:5:4:3:2:1
| group 15 = 1:2:3:4:5:4:3:2:1
| group 16 = 1:2:3:4:5:4:3:2:1
| group 17 = 1:2:3:4:5:4:3:2:1
| group 18 = 1:2:3:4:5:4:3:2:1
| group 19 = 1:2:3:4:5:4:3:2:1
| group 20 = 1:2:3:4:5:4:3:2:1
| group 21 = 1:2:3:4:5:4:3:2:1
| colors = Silver:Gray:Black:Red:Maroon:Yellow:Olive:Lime:Green:Aqua:Teal:Blue:Navy:Fuchsia:Purple:ForestGreen:Tomato:LightSeaGreen:RosyBrown:DarkOliveGreen:MediumVioletRed
| group names = Alabama:Alaska:Arizona:Arkansas:California:Colorado:Connecticut:Delaware:Florida:Georgia:Hawaii:Idaho:Illinois:Indiana:Iowa:Kansas:Kentucky:Louisiana:Maine:Maryland:Massachusetts
| x legends = 1920 : 1930 : 1940: 1950 : 1960 : 1970 : 1990 : 2000 : 2010
| units prefix = $
| units suffix = _billion
| stack = 1
}}
خطأ: الوظيفة "bar chart" غير موجودة.
If there are many values, x legends can be diluted by using delimiters with nothing in between:
{{ #invoke:Chart | bar chart
| group 1 = 1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:30
:31:32:33:34:35:36:37:38:39:40:41:42:43:44:45:46:47:48:49:50:51:52:53:54:55:56:57:58:59
| units suffix = _Things
| group names = Some
| x legends = ::::1940::::::::::1950::::::::::1960::::::::::1970::::::::::1980::::::::::1990::::
}}
خطأ: الوظيفة "bar chart" غير موجودة.
Drawing Pie charts: "pie chart"
Parameters
| parameter name | what it does |
|---|---|
| delimiter | string to delimit multiple values when given. default to colon ( : ). normally you do not want to touch this, it's provided for the off-chance you'll want to use colon as part of one of the parameters. |
| radius | number. The radius of the pie in pixels |
| slices | Tuples, in parenthesis. Use delimiter inside the tuple:
( Value1 : Name1 : Color1 : Link1 ) ( Value2 : Name2 : Color2 : Link2 ) ... The values are numbers. The numbers can be integers or decimal fractions, or using the scientific notation: 7.24e6, 7,240,000, or 7240000.00 are all acceptable for 7 Million and 240 thousands. Names are strings. Colors are optional. you can use any Web colors, such as "red" or "#FF0000". Up to 26 default colors are defined, but if your pie has more than 26 slices, you must define the colors of slice #27 and up. Links can be external or internal links, including linking to internal anchors and paragraphs in the same article, like so: [[Article|Tooltip]] for internal link, [[#Paragraph name|Tooltip]] for linking to an anchor in same article, or [http://example.org Tooltip] for external link. |
| slice n | alternative syntax to "slices". n is the slice number, beginning with 1. make sure not to skip: if you define "slice 1", "slice 2", "slice 4", "slice 5"..., skipping slice 3, only the first two slices will be shown. this syntax is incompatible with "slices", i.e., they should not be used in conjunction in the same invocation. Using both "slices" and "slice n" in the same invocation will cause unpredictable results. The value is like a single "tuple" as explained above, but without the parenthesis:
| slice 1 = Value1 : Name1 : Color1 : Link1 | slice 2 = Value2 : Name2 : Color2 : Link2 | ... This syntax allows you to use parenthesis in names, links, and colors. |
| percent | if used, the percentage of each slice will be calculated and added to the legend: so if you have two slices, like so: ( 1 : Younglings ) ( 3 : elders ), and use define "percent", the legends will become "Younglings: 1 (25%)" and "Elders: 3 (75%)", instead of simply "Younglings: 1" and "Elders: 3". Any non-empty value means "yes". To say "no", simply do not supply this parameter at all, or leave the value blank. |
| units prefix | used in the legend. e.g., defining "units prefix=$", values will show as "$500" instead of "500" in the legends |
| units suffix | ditto for units suffix. use, e.g. "Kg" so values will show as 88Kg instead of 88 in legend. underscore ("_") are replaced by spaces, to allow a space between the value and the suffix. |
| hide group legends | Setting to true prevents displaying of the group legends under the chart. Any non-empty value means "yes". To say "no", simply do not supply this parameter at all, or leave the value blank. |
Examples
{{#invoke:Chart|pie chart
| radius = 150
| slices =
( 1000000 : Apples )
( 2000000 : Bananas : gold)
( 1440000 : Apricots )
( 6.4e5 : Pears : : [[Pear|Pears]] )
( 750,000 : Pineapples )
| units suffix = _Tonne
| percent = true
}}
Note that we can leave the color empty to use the default, but in order to add the link to "Pear",
we had to mark the parameter by adding an extra delimiter to mark the omitted color parameter
Also note that the values can be provided with "language specific" format (like 1,000),
or scientific notation like 6.4e5. In the legends, numbers will always be displayed in
language-adjusted mode (can look different if module imported to other wikis).
خطأ: الوظيفة "pie chart" غير موجودة.
An example for the alternative syntax with "slice 1", "slice 2" etc.
{{#invoke:chart|pie chart
|radius= 200
|units suffix = _Units
| slice 1 = 1 : 1
| slice 2 = 7 : 7
| slice 3 = 8 : 8
| slice 4 = 9 : 9
| slice 5 = 10 : 10
| slice 6 = 11 : 11
| slice 7 = 12 : 12
| slice 8 = 13 : 13
| slice 9 = 14 : 14
| slice 10 = 15 : 15
| slice 11 = 16 : 16
| slice 12 = 17 : 17
| slice 13 = 18 : 18
| slice 14 = 19 : 19
| slice 15 = 20 : 20
| slice 16 = 21 : 21
| slice 17 = 22 : 22
| slice 18 = 23 : 23
| slice 19 = 24 : 24
| slice 20 = 25 : 25
| slice 21 = 26 : 26
| slice 22 = 27 : 27
| slice 23 = 28 : 28
| slice 24 = 29 : 29
| slice 25 = 30 : 30
| slice 26 = 31 : 31
| percent = true
}}
خطأ: الوظيفة "pie chart" غير موجودة.
local p = {}
-- ============================================================
-- Module:Chart
-- Marefa compatibility module for MediaWiki 1.42
--
-- Reads local JsonConfig .tab datasets with mw.ext.data.get()
-- and renders line charts through Extension:Graph / Vega.
-- ============================================================
-- ------------------------------------------------------------
-- Utility functions
-- ------------------------------------------------------------
local function trim(s)
if s == nil then
return nil
end
return mw.text.trim(tostring(s))
end
local function errorMessage(msg)
return '<strong class="error">خطأ في الرسم البياني: ' ..
mw.text.encode(msg) ..
'</strong>'
end
-- ------------------------------------------------------------
-- Load a local JsonConfig tabular dataset.
--
-- Accepts:
--
-- Chart test.tab
-- Data:Chart test.tab
-- New York City skyscraper growth.chart
--
-- A .chart suffix is converted to .tab because this
-- compatibility module currently reads the underlying
-- tabular dataset rather than Wikimedia's Chart definition.
-- ------------------------------------------------------------
local function loadDataset(name)
name = trim(name)
if not name or name == '' then
return nil, 'لم يُحدد ملف البيانات.'
end
name = name:gsub('^Data:', '')
name = name:gsub('%.chart$', '.tab')
if not name:match('%.tab$') then
name = name .. '.tab'
end
if not mw.ext
or not mw.ext.data
or not mw.ext.data.get then
return nil, 'امتداد JsonConfig غير متاح.'
end
local ok, data = pcall(
mw.ext.data.get,
name
)
if not ok then
return nil, 'تعذر تحميل Data:' .. name
end
if data == false
or type(data) ~= 'table' then
return nil, 'تعذر تحميل Data:' .. name
end
if type(data.data) ~= 'table' then
return nil,
'لا يحتوي Data:' ..
name ..
' على جدول بيانات صالح.'
end
return data, nil
end
-- ------------------------------------------------------------
-- Parse column list.
--
-- Example:
--
-- y=2,3,4
--
-- ------------------------------------------------------------
local function parseColumns(value)
local result = {}
for n in tostring(value or ''):gmatch('%d+') do
result[#result + 1] = tonumber(n)
end
return result
end
-- ------------------------------------------------------------
-- Parse legend labels separated with |
--
-- Example:
--
-- labels=أعلى من 150 م|أعلى من 200 م|أعلى من 300 م
--
-- ------------------------------------------------------------
local function parseLabels(value)
local result = {}
if not value or value == '' then
return result
end
for item in mw.text.gsplit(
value,
'|',
true
) do
result[#result + 1] =
mw.text.trim(item)
end
return result
end
-- ------------------------------------------------------------
-- Determine a useful field label from the JsonConfig schema.
-- ------------------------------------------------------------
local function getFieldLabel(
dataset,
column,
lang
)
if not dataset.schema
or not dataset.schema.fields
or not dataset.schema.fields[column] then
return 'السلسلة ' ..
tostring(column)
end
local field =
dataset.schema.fields[column]
if type(field.title) == 'table' then
return field.title[lang]
or field.title.ar
or field.title.en
or field.name
or (
'السلسلة ' ..
tostring(column)
)
end
if type(field.title) == 'string' then
return field.title
end
return field.name
or (
'السلسلة ' ..
tostring(column)
)
end
-- ------------------------------------------------------------
-- Convert tabular data into Vega rows.
--
-- Source:
--
-- [1900, 0, 0, 0]
--
-- Becomes:
--
-- {
-- x = 1900,
-- series1 = 0,
-- series2 = 0,
-- series3 = 0
-- }
--
-- ------------------------------------------------------------
local function makeValues(
dataset,
xColumn,
yColumns
)
local values = {}
for _, row in ipairs(dataset.data) do
if type(row) == 'table' then
local x =
tonumber(row[xColumn])
if x then
local item = {
x = x
}
local hasValue = false
for i, column
in ipairs(yColumns) do
local value =
tonumber(row[column])
if value ~= nil then
item[
'series' .. i
] = value
hasValue = true
end
end
if hasValue then
values[#values + 1] =
item
end
end
end
end
return values
end
-- ------------------------------------------------------------
-- Generate explicit X-axis tick values.
--
-- Example:
--
-- min = 1900
-- max = 2030
-- step = 10
--
-- produces:
--
-- 1900, 1910, 1920 ... 2030
--
-- ------------------------------------------------------------
local function makeXTicks(
xMin,
xMax,
xStep
)
if not xMin
or not xMax
or not xStep
or xStep <= 0 then
return nil
end
if xMax < xMin then
return nil
end
local ticks = {}
local value = xMin
local guard = 0
while value <= xMax do
ticks[#ticks + 1] = value
value = value + xStep
guard = guard + 1
-- Prevent accidental creation of
-- extremely large Vega specifications.
if guard > 1000 then
break
end
end
-- If the step does not land exactly on xMax,
-- include the requested maximum as the last tick.
if #ticks > 0
and ticks[#ticks] < xMax then
ticks[#ticks + 1] = xMax
end
return ticks
end
-- ============================================================
-- Main line-chart renderer
-- ============================================================
function p.line(frame)
local args = frame.args
-- --------------------------------------------------------
-- Allow invocation through Template:Chart.
-- --------------------------------------------------------
if frame:getParent() then
local parentArgs =
frame:getParent().args
for k, v in pairs(parentArgs) do
if args[k] == nil
or args[k] == '' then
args[k] = v
end
end
end
-- --------------------------------------------------------
-- Dataset
-- --------------------------------------------------------
local datasetName =
trim(args.data)
or trim(args[1])
if not datasetName
or datasetName == '' then
return errorMessage(
'يجب تحديد وسيط data.'
)
end
local dataset, loadError =
loadDataset(datasetName)
if not dataset then
return errorMessage(loadError)
end
-- --------------------------------------------------------
-- Columns
-- --------------------------------------------------------
local xColumn =
tonumber(args.x)
or 1
local yColumns =
parseColumns(
args.y or '2'
)
if #yColumns == 0 then
yColumns = {2}
end
-- --------------------------------------------------------
-- Convert dataset to Vega values.
-- --------------------------------------------------------
local values =
makeValues(
dataset,
xColumn,
yColumns
)
if #values == 0 then
return errorMessage(
'لم يُعثر على بيانات رقمية قابلة للرسم.'
)
end
-- --------------------------------------------------------
-- Dimensions
-- --------------------------------------------------------
local width =
tonumber(args.width)
or 700
local height =
tonumber(args.height)
or 400
-- --------------------------------------------------------
-- Language and titles
-- --------------------------------------------------------
local lang =
trim(args.lang)
or 'ar'
local title =
trim(args.title)
or ''
local xTitle =
trim(args['x-title'])
or 'السنة'
local yTitle =
trim(args['y-title'])
or 'العدد'
-- --------------------------------------------------------
-- Legend labels
-- --------------------------------------------------------
local labels =
parseLabels(args.labels)
for i, column
in ipairs(yColumns) do
if not labels[i]
or labels[i] == '' then
labels[i] =
getFieldLabel(
dataset,
column,
lang
)
end
end
-- ========================================================
-- X-axis domain
-- ========================================================
local xMin =
tonumber(args['x-min'])
local xMax =
tonumber(args['x-max'])
local xStep =
tonumber(args['x-step'])
if xMin and xMax and xMax <= xMin then
return errorMessage(
'يجب أن تكون قيمة x-max أكبر من x-min.'
)
end
local xScale = {
name = 'x',
type = 'linear',
domain = {
data = 'table',
field = 'x'
},
range = 'width',
zero = false,
nice = false
}
if xMin then
xScale.domainMin = xMin
end
if xMax then
xScale.domainMax = xMax
end
-- --------------------------------------------------------
-- Generate X-axis tick values if requested.
-- --------------------------------------------------------
local xTicks =
makeXTicks(
xMin,
xMax,
xStep
)
-- ========================================================
-- Vega specification
-- ========================================================
local spec = {
version = 2,
width = width,
height = height,
padding = {
top =
title ~= ''
and 45
or 20,
left = 65,
right = 25,
bottom = 55
},
-- ----------------------------------------------------
-- Data
-- ----------------------------------------------------
data = {
{
name = 'table',
values = values
}
},
-- ----------------------------------------------------
-- Scales
-- ----------------------------------------------------
scales = {
xScale,
{
name = 'y',
type = 'linear',
range = 'height',
domain = {
data = 'table',
fields = {}
},
zero = true,
nice = true
},
{
name = 'color',
type = 'ordinal',
range = {
'#36c',
'#d33',
'#14866d',
'#a66bbe',
'#f28500',
'#6b4c9a'
},
domain = {}
}
},
-- ----------------------------------------------------
-- Axes
-- ----------------------------------------------------
axes = {
{
type = 'x',
scale = 'x',
title = xTitle,
grid = false,
format = 'd'
},
{
type = 'y',
scale = 'y',
title = yTitle,
grid = true,
tickCount = 6
}
},
-- ----------------------------------------------------
-- Marks will be added below.
-- ----------------------------------------------------
marks = {}
}
-- ========================================================
-- Explicit X ticks
-- ========================================================
if xTicks
and #xTicks > 0 then
spec.axes[1].values =
xTicks
else
spec.axes[1].tickCount = 7
end
-- ========================================================
-- Y scale domains
-- ========================================================
for i = 1, #yColumns do
spec.scales[2]
.domain
.fields[
#spec.scales[2]
.domain
.fields + 1
] = {
data = 'table',
field = 'series' .. i
}
spec.scales[3]
.domain[
#spec.scales[3]
.domain + 1
] = labels[i]
end
-- ========================================================
-- Add one line for each selected series
-- ========================================================
for i = 1, #yColumns do
spec.marks[
#spec.marks + 1
] = {
type = 'line',
from = {
data = 'table'
},
properties = {
enter = {
x = {
scale = 'x',
field = 'x'
},
y = {
scale = 'y',
field =
'series' .. i
},
stroke = {
scale = 'color',
value = labels[i]
},
strokeWidth = {
value = 2
}
}
}
}
end
-- ========================================================
-- Optional chart title
-- ========================================================
if title ~= '' then
spec.marks[
#spec.marks + 1
] = {
type = 'text',
properties = {
enter = {
x = {
field = {
group = 'width'
},
mult = 0.5
},
y = {
value = -25
},
text = {
value = title
},
align = {
value = 'center'
},
baseline = {
value = 'middle'
},
fontSize = {
value = 16
},
fontWeight = {
value = 'bold'
}
}
}
}
end
-- ========================================================
-- Legend
-- ========================================================
if #yColumns > 1 then
spec.legends = {
{
fill = 'color',
title = ''
}
}
end
-- ========================================================
-- Encode and render through Extension:Graph
-- ========================================================
local json =
mw.text.jsonEncode(spec)
return frame:extensionTag(
'graph',
json,
{}
)
end
return p