XQuery/Google 图表 Sparkline
外观
< XQuery
您希望使用通用图表服务(如 Google 图表)创建易于使用的专用图表。
该 GoogleChart API 从 URL 行中传递的数据创建 PNG 格式的图表。
该服务的一种用途是生成 Tufte sparkline。此脚本使用随机数据来生成一个小的类似 sparkline 的图形。经过更多工作,应该能够添加额外的功能,例如最小值、最大值和正常带。折线图 (cht=lc) 包含轴,但可以使用未记录的功能将其删除,其中图表类型指定为 lfi [1]
该脚本在 XQuery 中使用函数重载,该函数允许两个函数具有相同的名称,但参数数量不同。更通用的函数具有用于值序列以及用于缩放值的最小值和最大值的参数。第二个函数(具有相同的名称)仅接受值,并从数据中计算最小值和最大值,然后调用更通用的函数来完成任务。
(: This script illustrates the use of the GoogleChart API to generate a sparkline-like graphic
:)
declare option exist:serialize "method=html media-type=text/html";
declare function local:simple-encode(
$vals as xs:decimal* ,
$min as xs:decimal,
$max as xs:decimal)
as xs:string {
(: encode the sequence of numbers as a string according to the simple encoding scheme.
the data values are encoded in the characters A-Z,a-z,0-9 giving a range from 0 to 61
:)
let $scale := 62.0 div ($max - $min)
let $simpleEncode := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
return
string-join( for $x in $vals
let $n := floor( ($x - $min) * $scale)
return substring($simpleEncode,$n+1,1)
,"")
};
declare function local:simple-encode($vals as xs:decimal*) as xs:string {
(: compute the minimulm and maximum values, then call the more general function to encode :)
let $min := min($vals)
let $max := max($vals)
return local:simple-encode($vals,$min,$max)
};
declare function local:sparkline(
$data as xs:decimal* ,
$fontHeight as xs:integer,
$pointSize as xs:integer,
$label as xs:string )
as element(span) {
(: create a span element containing the line chart of the data, the name of the data set
and the last data value
fontHeight and pointSize are defined in pixels
:)
let $codeString := local:simple-encode($data)
let $width := count($data) * $pointSize
let $last := $data[last()]
let $title :=concat( "Graph of ",$label, " data: ",count($data)," values, min ",min($data), " max ", max($data))
return
<span>
<img src="http://chart.apis.google.com/chart?chs={$width}x{$fontHeight}&chd=s:{$codeString}&cht=lfi"
alt="{$title}" title="{$title}"
/>
<font style="font-size:{$fontHeight}px"> {$label} {$last}</font>
</span>
};
(: generate some random data :)
let $data := for $i in (1 to 100) return floor(util:random() * 10)
return local:sparkline($data,50,2,"Random")