Module:Television ratings graph: Difference between revisions

Content deleted Content added
Update to live
oops typo
 
(28 intermediate revisions by 10 users not shown)
Line 1:
-- This module implements {{Television ratings graph}}.
 
local contrast_ratio = require('Module:Color contrast')._ratio
 
--------------------------------------------------------------------------------
Line 7 ⟶ 9:
 
local TVRG = {}
 
-- Convert HEX codes to RGB values
function TVRG.hex2rgb(hex)
hex = hex:gsub('#', '')
if #hex == 3 then
-- #000 format
return tonumber("0x"..hex:sub(1,1)..hex:sub(1,1))/256, tonumber("0x"..hex:sub(2,2)..hex:sub(2,2))/256,
tonumber("0x"..hex:sub(3,3)..hex:sub(3,3))/256
else
-- #000000 format
return tonumber("0x"..hex:sub(1,2))/256, tonumber("0x"..hex:sub(3,4))/256, tonumber("0x"..hex:sub(5,6))/256
end
end
 
-- Allow usages of {{N/A}} cells
Line 45 ⟶ 34:
function TVRG.new(frame,args)
args = args or {}
local categories = ''
local title = mw.title.getCurrentTitle()
-- Variables
Line 55 ⟶ 46:
-- Create the timeline
-- Bar width
local barwidth
if #args < 20 then barwidth = 8
elseif #args > 75 then barwidth = 6
else barwidth = 7 end
-- Basis parameters
timeline = timeline .. "ImageSize = width:" .. (args.width or 1000) .. " height:" .. (args.height or 300) .. "\n"
timeline = timeline .. "PlotArea = left:50 bottom:70 top:20 right:50\n"
timeline = timeline .. "AlignBars = justify\n"
timeline = timeline .. "Colors =\n"
timeline = timeline .. " id:a value:gray(0.7)\n"
-- Number of actual viewer numbers
local numberargs = 0
for k,v in pairs(args) do
if (string.lower(v) == 'n/a') or (not string.match(k,'[^%d]+') and not string.match(v,'[^%d%.]+')) then numberargs = numberargs + 1 end
end
 
-- Determine number of seasons
local num_seasons = -1
Line 77 ⟶ 61:
end
end
if num_seasons < 1 then
num_seasons = 1
end
 
-- Determine number of episodes and subtract averages if included (they should be equal to the number of seasons)
local num_episodes
if average == 1 then
num_episodes = numberargs-num_seasons
else
num_episodes = numberargs
end
 
-- Bar and graph width
local barwidth
if args.bar_width then barwidth = args.bar_width
-- Colour and legend variables
elseif num_episodes >= 120 then barwidth = 6
local season = 1
elseif num_episodes >= 100 then barwidth = 7
for season = 1,num_seasons do
elseif num_episodes >= 80 then barwidth = 8
local r,g,b = TVRG.hex2rgb(args['color' .. season] or '#006600')
elseif num_episodes >= 50 then barwidth = 9
timeline = timeline .. " id:season" .. season .. " value:rgb("..r..","..g..","..b..") legend:" ..
elseif num_episodes >= 20 then barwidth = 10
string.gsub(string.gsub((args["legend" .. season] or season_title .. " " .. season), ' ', '_'), "''(.-)''", '%1') .. "\n"
else barwidth = 11
season = season + 1
end
 
-- Determine maximum viewer figure
local maxviewers = -1
local multiple = 'millions'
for k,v in pairs(args) do
local num = tonumber(v)
Line 95 ⟶ 94:
end
end
if maxviewers <= 1.5 then
multiple = 'thousands'
maxviewers = maxviewers*1000
for k, v in pairs(args) do
local num = tonumber(v)
if tonumber(k) ~= nil and num ~= nil then args[k] = tostring(num*1000) end
end
end
local is_singular = num_episodes == 1
 
-- FurtherBasis parameters, with rounded-up viewer figures as maximum period
timeline = timeline .. "\nImageSize = width:" .. (is_singular and 200 or 'auto') .. " height:"..(args.height or 500).. (is_singular and '' or " barincrement:"..(barwidth+(num_episodes == 2 and 16 or 4))).."\n"
timeline = timeline .. "DateFormat = x.y\n"
timeline = timeline .. "Period \nPlotArea = fromleft:050 tillbottom:"50 ..top:10 math.ceil(maxviewers) .. "right:100\n"
timeline = timeline .. "TimeAxis \nAlignbars = orientation:verticaljustify\n"
timeline = timeline .. "ScaleMajor\nPeriod = gridcolorfrom:a0 incrementtill:1 start:0"..math.ceil(maxviewers).."\n"
timeline = timeline .. "Legend \nTimeAxis = orientation:horizontalvertical format:y\n"
-- Colors
-- Interval parameter set to prevent overlapping bars
timeline = timeline .. "\nColors =\n"
local bar = 1
if args.intervals then
for season = 1,num_seasons do
timeline = timeline .. "BarData =\n"
args["color" .. season] = args["color" .. season] or '#CCCCFF'
for k,v in pairs(args) do
hex = args["color" .. season]:gsub("#","")
if tonumber(k) ~= nil and (tonumber(v) ~= nil or v == '') then
if #hex == 3 then
timeline = timeline .. " bar:"..bar.." text:"..((bar == 1 or bar % args.intervals == 0) and bar or '&nbsp;').."\n"
-- If it's 3 hex chars then make it six instead
bar = bar + 1
hex = hex:sub(1,1) .. hex:sub(1,1) .. hex:sub(2,2) .. hex:sub(2,2) .. hex:sub(3,3) .. hex:sub(3,3)
end
end
rgbR = tonumber("0x"..hex:sub(1,2))/256
rgbG = tonumber("0x"..hex:sub(3,4))/256
rgbB = tonumber("0x"..hex:sub(5,6))/256
local legend = season_title.."_"..(args["legend" .. season] and args["legend" .. season] or season )
timeline = timeline .. "\n id:season"..season.." value:rgb("..rgbR..", "..rgbG..", "..rgbB..") legend:"..legend:gsub(" ", "_").."\n"
end
timeline = timeline .. "\n id:bars value:gray(0.95)"
timeline = timeline .. "\nLegend = orientation:vertical position:right\n"
timeline = timeline .. "\nBackgroundColors = bars:bars\n"
timeline = timeline .. "\nScaleMajor = unit:year increment:"..(multiple == 'thousands' and 100 or 1).." start:0\n"
timeline = timeline .. "\nScaleMinor = unit:year increment:"..(multiple == 'thousands' and 100 or 1).." start:0\n"
 
local x_intervals = args.x_intervals or (num_episodes >= 80 and 2 or 1)
-- Plot data
 
timeline = timeline .. "PlotData =\n"
timeline = timeline .. " width:" .. barwidth .. "\nBarData=\n"
for episode = 1,num_episodes do
episodetext = ((episode % x_intervals == 0) and episode or "")
timeline = timeline .. "\n bar:"..episode.." text:"..episodetext.."\n"
end
-- Add bars to timeline, one per viewer figure
local bar = 1
local season = 10
local thisseason = 0
local counted_episodes = 0
timeline = timeline .. "\nPlotData=\n"
for k,v in pairs(args) do
timeline = timeline .. "\n width:"..barwidth.." textcolor:black align:left anchor:from shift:(10,-4)\n"
if tonumber(k) ~= nil then
if v == '-' then
for k,v in ipairs(args) do
-- Hyphen means new season, so change colour
if string.lower(v) == 'n/a' then v = '' end
timeline = timeline .. " color:season" .. season .. "\n"
season = season + 1
if v == '-' then
-- Determine highest number of episodes in a season
-- Hyphen means new season
if thisseason > longestseason then
season = season + 1
longestseason = thisseason
 
end
-- Determine highest number of counted_episodes in a season
thisseason = 0
if thisseason > longestseason then
elseif average == 0 or (average == 1 and (args[k+1] == '-' or args[k+1] == nil) == false) then
longestseason = thisseason
-- Include bar for viewer figure, do not include if averages are included and the next parameter is a new season marker
timeline = timeline .. " bar:" .. bar .. " from:start till:" .. (v ~= '' and v or 'start') .. "\n"
thisseason = thisseason + 1
bar = bar + 1
end
thisseason = 0
elseif average == 0 or (average == 1 and args[k+1] ~= '-' and args[k+1] ~= nil) then
-- Include bar for viewer figure, do not include if averages are included and the next parameter is a new season marker
timeline = timeline .. "\n bar:"..bar.." from:0 till:"..(v ~= '' and v or 0).." color:season"..season.."\n"
-- Increment tracking variables
counted_episodes = counted_episodes + 1
thisseason = thisseason + 1
bar = bar + 1
end
end
Line 147 ⟶ 178:
longestseason = thisseason
end
-- Axis labels
local countryDisplayUS, countryDisplayUK, countryDisplayOther
if args.country ~= nil and args.country ~= '' then
if args.country == "U.S." or args.country == "US" or args.country == "United States" then countryDisplayUS = 'U.S.'
elseif args.country == "U.K." or args.country == "UK" or args.country == "United Kingdom" then countryDisplayUK = 'UK'
else countryDisplayOther = args.country end
end
-- If there's a title, add it with the viewers caption, else just display the viewers caption by itself
if args.title ~= nil and args.title ~= '' then
root:wikitext("'''''" .. args.title .. "''" .. "&#8202;" .. ": " .. ((countryDisplayUS or countryDisplayUK or countryDisplayOther) or "") .. ((countryDisplayUS or countryDisplayUK or countryDisplayOther) and " v" or "V") .. "iewers per episode (" .. multiple .. ")'''"):css('margin-top', '1em')
else
root:wikitext("'''Viewers per episode (" .. multiple .. ")'''"):css('margin-top', '1em')
end
root:tag('div'):css('clear','both')
-- Add timeline to div
if args.nographno_graph == nil then
if num_episodes > 100 then
root:node(frame:extensionTag('timeline', timeline))
root:tag('div'):wikitext("Too many episodes to display graph (maximum 100).")
if title.namespace == 0 then
categories = categories .. '[[Category:Articles using Template:Television ratings graph with excessive figures]]'
end
else
timelineBase = frame:preprocess("<timeline>"..timeline.."</timeline>")
root:node(timelineBase)
root:tag('div'):css('clear','both')
end
end
-- Create ratings table
if args.notableno_table == nil then
local rtable = mw.html.create('table')
:addClass('wikitable')
:css('text-align', 'center')
-- Create headers rows
-- If there's a title, add it with the viewers caption, else just display the viewers caption by itself
local row = rtable:tag('tr')
if args.title ~= nil and args.title ~= '' then
row:tag('th'):wikitext(season_title)
rtable:tag('caption'):wikitext("''" .. args.title .. "''" .. frame:expandTemplate{ title = 'hsp' } .. ": Viewers per episode (millions)")
:attr('scope','col')
else
:attr('colspan','2')
rtable:tag('caption'):wikitext("Viewers per episode (millions)")
:attr('rowspan','2')
end
:css('padding-left', '.8em')
:css('padding-right', '.8em')
-- Headers rows for episodes 1 to highest number of episodes
local row = rtable:tag('tr')
row:tag('th'):wikitext(season_title)
:attr('colspan','2')
for i = 1,longestseason do
row:tag('th')
:attr('scope','colcolgroup')
:attr('colspan',longestseason)
:wikitext(frame:expandTemplate{ title='abbr', args={ 'Ep.', 'Episode' } } .. ' ' .. i)
:wikitext("Episode number")
end
:css('padding-left', '.8em')
:css('padding-right', '.8em')
-- Average column
if average == 1 then
-- Average column
row:tag('th')
if average == 1 then
:attr('scope','col')
row:wikitexttag("'th'Average''")
:attr('scope','col')
end
:attr('rowspan','2')
:wikitext("Average")
:css('padding-left', '.8em')
:css('padding-right', '.8em')
end
 
local row = rtable:tag('tr')
for i = 1,longestseason do
row:tag('th')
:attr('scope','col')
:wikitext(i)
end
local season = 1
Line 195 ⟶ 260:
-- Spanning empty cells with {{N/A}}
if thisseason < longestseason then
row:node(TVRG.NACell(frame,"N/A"):attr('colspan',longestseason-thisseason))
end
Line 215 ⟶ 280:
row:tag('th')
:css('background-color', args['color' .. season])
:css('width','10px14px')
:css('padding','0')
row:tag('th')
Line 226 ⟶ 292:
elseif average == 0 or (average == 1 and args[k+1] ~= '-' and args[k+1] ~= nil) then
-- Viewer figures, either as a number or TBD
if string.lower(v) ~== 'n/a' then
row:node(TVRG.NACell(frame,"N/A"))
elseif v ~= '' then
row:tag('td'):wikitext(v)
:css('width', '35px')
else
row:node(TVRG.NACell(frame,"TBD"))
Line 237 ⟶ 306:
-- Finish by checking if final row needs {{N/A}} cells
if average == 0 and thisseason < longestseason then
row:node(TVRG.NACell(frame,"N/A"):attr('colspan',longestseason-thisseason))
end
-- Add table to div root and return
root:node(rtable)
root:tag('div'):css('clear','both')
end
local current_monthyear = os.date("%B %Y")
local span = mw.html.create('span'):wikitext(frame:expandTemplate{title='Citation needed', args={date=current_monthyear}})
if countryDisplayUS then
root:wikitext("<small>Audience measurement performed by [[Nielsen Media Research]]</small>" .. (args.refs ~= '' and args.refs or tostring(span)))
elseif countryDisplayUK then
root:wikitext("<small>Audience measurement performed by [[Broadcasters' Audience Research Board]]</small>" .. (args.refs ~= '' and args.refs or tostring(span)))
else
root:wikitext("<small>Source: </small>" .. (args.refs ~= '' and args.refs or tostring(span)))
end
return tostring(root) .. categories
end