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")