flot中文API(转载)
Flot Reference
flot參考文檔
--------------
Consider a call to the plot function:
下面是對繪圖函數plot的調用:
?? var plot = $.plot(placeholder, data, options)
The placeholder is a jQuery object or DOM element or jQuery expression
that the plot will be put into. This placeholder needs to have its
width and height set as explained in the README (go read that now if
you haven't, it's short). The plot will modify some properties of the
placeholder so it's recommended you simply pass in a div that you
don't use for anything else. Make sure you check any fancy styling
you apply to the div, e.g. background images have been reported to be a
problem on IE 7.
占位符placeholder是一個jQuery對象或者DOM元素或者jQuery表單式,繪圖函數將把圖表畫在placeholder內。
這個占位符需要設置高寬(這在README文檔里面已經介紹過,如果你還沒有閱讀過現在就去閱讀吧,文檔很短)。
plot函數畫圖時將修改這個占位符的內容,因此你最好使用一個空的DIV元素作為占位符,另外注意不要給占位符
設置花哨的樣式,比如,在IE7.0下,給占位符設置背景圖將會出錯。
The format of the data is documented below, as is the available
options. The "plot" object returned has some methods you can call.
These are documented separately below.
函數可以使用的數據格式會在后面說明,plot返回對象有一些方法可供調用,在后面會分開介紹。
Note that in general Flot gives no guarantees if you change any of the
objects you pass in to the plot function or get out of it since
they're not necessarily deep-copied.
另外請注意,flot不保證plot函數內的對象被修改或刪除后仍然能正常工作(廢話)。
Data Format
數據格式
-----------
The data is an array of data series:
flot的數據是一個數列數組(plot函數中的data參數:每條曲線一個data項參數,繪制多條曲線時,是一個數組,每個數組元素是一條曲線的data項參數):
? [ series1, series2, ... ]
A series can either be raw data or an object with properties. The raw
data format is an array of points:
數列可以是原始數據,也可以是數據對象,原始數據格式是由一組表示數據點的坐標值的數組構成:
? [ [x1, y1], [x2, y2], ... ]
E.g.
? [ [1, 3], [2, 14.01], [3.5, 3.14] ]
Note that to simplify the internal logic in Flot both the x and y
values must be numbers (even if specifying time series, see below for
how to do this). This is a common problem because you might retrieve
data from the database and serialize them directly to JSON without
noticing the wrong type. If you're getting mysterious errors, double
check that you're inputting numbers and not strings.
請注意,flot的縱橫坐標值都必須是數字(即使用時間數列也是,后面會介紹到),
這是個很常見的錯誤,因為你很可能從數據庫獲取數據后沒有檢查數據類型就直接轉化成json對象使用。
如果你覺得遇到了莫名其妙的錯誤,請確認一下你輸入的是數字而不是字符串。
If a null is specified as a point or if one of the coordinates is null
or couldn't be converted to a number, the point is ignored when
drawing. As a special case, a null value for lines is interpreted as a
line segment end, i.e. the points before and after the null value are
not connected.
如果坐標為值為空 ,或者其中的一個坐標值為空,或者不是數字,或者說不能轉換為數字,那么這個節點將被忽略,
并且該節點前后的2個節點之間不會使用直線來連接。
Lines and points take two coordinates. For bars, you can specify a
third coordinate which is the bottom of the bar (defaults to 0).
折線圖和散點圖每個節點有2個參數,直方圖則有3個參數,第三個參數來指定直方圖的底部位置(缺省值是0)。
The format of a single series object is as follows:
單個圖表對象的數據格式參數如下所示:
? {
??? color: color or number?? //顏色
??? data: rawdata? //數據
??? label: string? //曲線名稱
??? lines: specific lines options? //折線圖坐標參數
??? bars: specific bars options?? //直方圖坐標參數
??? points: specific points options? //散點圖坐標參數
??? xaxis: 1 or 2? //使用哪一條X軸,如果某條數軸沒有被任何一條曲線使用,該數軸不會在圖表上出現
??? yaxis: 1 or 2? //使用哪一條Y軸
??? clickable: boolean? //允許監聽鼠標點擊事件
??? hoverable: boolean? //允許監聽鼠標懸停事件
??? shadowSize: number //曲線陰影
? }
You don't have to specify any of them except the data, the rest are
options that will get default values. Typically you'd only specify
label and data, like this:
一般情況下你無須設置每一個參數, 你只需要設置其中幾個特定的參數即可,其他參數會使用默認值。例如:
? {
??? label: "y = 3",
??? data: [[0, 3], [10, 3]]
? }
The label is used for the legend, if you don't specify one, the series
will not show up in the legend.
label用于指定曲線名稱,如果沒有設置label的值,圖表標題區域不會出現。
If you don't specify color, the series will get a color from the
auto-generated colors. The color is either a CSS color specification
(like "rgb(255, 100, 123)") or an integer that specifies which of
auto-generated colors to select, e.g. 0 will get color no. 0, etc.
如果沒有設置曲線顏色,程序會自動采用默認顏色(options項里的colors數列)。顏色值可以是CSS顏色格式(RGB格式、16進制顏色、WEB通用顏色名),
還可以是數字編號,數字編號表示顏色數列里面顏色的編號。
The latter is mostly useful if you let the user add and remove series,
in which case you can hard-code the color index to prevent the colors
from jumping around between the series.
如果你允許用戶重置或刪除曲線,后者會比較有用,你可以在代碼里面設置曲線使用的默認顏色的序號防止相同顏色在不用曲線間重復出現。
The "xaxis" and "yaxis" options specify which axis to use, specify 2
to get the secondary axis (x axis at top or y axis to the right).
E.g., you can use this to make a dual axis plot by specifying
{ yaxis: 2 } for one data series.
xaxis" 和 "yaxis" 設置曲線使用的數軸(第二條X軸是頂部橫軸,第二條Y軸是右邊的縱軸),你可以使用這個屬性制作雙數軸曲線
"clickable" and "hoverable" can be set to false to disable
interactivity for specific series if interactivity is turned on in
the plot, see below.
"clickable" 和 "hoverable"用于關閉該曲線的鼠標點擊效果或鼠標懸停效果,具體說明看后面。
(options中的"clickable" 或 "hoverable"設置為true時可以在某條曲線的data里設置"clickable" 或 "hoverable"為false,但options中設置為false時,不能在這里設置為true)
The rest of the options are all documented below as they are the same
as the default options passed in via the options parameter in the plot
commmand. When you specify them for a specific data series, they will
override the default options for the plot for that data series.
其他參數在后面介紹,他們與plot函數的"options"參數的設置項是一樣的,
如果你為某條曲線在data里面設置了這些參數的值,他們會覆蓋掉options的默認值。
Here's a complete example of a simple data specification:
下面是一個簡單例子,設置了2條曲線的參數:
? [ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] },
??? { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] } ]
Plot Options
plot的options參數
------------
All options are completely optional. They are documented individually
below, to change them you just specify them in an object, e.g.
options的所有選項都是可選的,他們都有默認值,后面會逐條對他們進行講解,如果要修改這些選項的默認值你只需要明確指定他們的值即可,例如:
? var options = {
??? series: {
????? lines: { show: true },
????? points: { show: true }
??? }
? };
? $.plot(placeholder, data, options);
Customizing the legend
legend:定制曲線圖表標題
======================
? legend: {
??? show: boolean
??? labelFormatter: null or (fn: string, series object -> string)
??? labelBoxBorderColor: color
??? noColumns: number
??? position: "ne" or "nw" or "se" or "sw"
??? margin: number of pixels or [x margin, y margin]
??? backgroundColor: null or color
??? backgroundOpacity: number between 0 and 1
??? container: null or jQuery object/DOM element/jQuery expression
? }
The legend is generated as a table with the data series labels and
small label boxes with the color of the series. If you want to format
the labels in some way, e.g. make them to links, you can pass in a
function for "labelFormatter". Here's an example that makes them
clickable:
legend 用于生成圖表標題,圖表標題以表格的方式顯示在曲線圖上,內容包括每條曲線的名稱及其對應顏色,
如果你想定制圖表標題的格式,比如做成超鏈接,你可以在"labelFormatter"項使用函數來定制,下面的例子把圖表標題做成鏈接
? labelFormatter: function(label, series) {
??? // series is the series object for the label? //series是名稱為label的曲線的數據對象
??? return '<a href="#' + label + '">' + label + '</a>';
? }
"noColumns" is the number of columns to divide the legend table into.
"noColumns" 用于設置legend表格的列數
"position" specifies the overall placement of the legend within the
plot (top-right, top-left, etc.) and margin the distance to the plot
edge (this can be either a number or an array of two numbers like [x,
y]). "backgroundColor" and "backgroundOpacity" specifies the
background. The default is a partly transparent auto-detected
background.
position:用于指定legend在曲線圖內的位置,"ne"東北角,"se"東南 , "nw"西北 , "sw"西南
margin: 設置legend與曲線圖邊框的距離,可以是x y軸偏移量的數值對[x,y]也可以是單個數字,單個數字值表示相對x,y軸的偏移量使用相同的值
采用哪條X軸和Y軸作為參照物取決于position的值
backgroundColor: 設置legend的背景顏色
backgroundOpacity: 設置legend背景的透明度
If you want the legend to appear somewhere else in the DOM, you can
specify "container" as a jQuery object/expression to put the legend
table into. The "position" and "margin" etc. options will then be
ignored. Note that Flot will overwrite the contents of the container.
如果你想把legend放在其他DOM元素內,可以為container設定一個值,
container的值可以是jQuery對象或表達式,例如:container: $("#showChartLegend"),把標題顯示在id為showChartLegend的div或其他容器類標簽內,
container為legend指定容器后,"position" 和 "margin" 等與圖表相關的位置屬性會被忽略,
另外請注意,container指定的容器內容會被覆蓋掉。
Customizing the axes
數軸定制
====================
? xaxis, yaxis, x2axis, y2axis: {
??? mode: null or "time"? //數軸是否為時間模式
??? min: null or number? //數軸最小值
??? max: null or number? //數軸最大值
??? autoscaleMargin: null or number? //按百分比為數軸延長一小段來縮放曲線以避免曲線最遠的數據點出現在圖表邊框上
???????????????????????????????????? //延長的距離為單位刻度的整數倍,且剛好不小于(max-min)*number,其中min端增加1個刻度單位的長度,當對應數軸的min和max值至少一個為null時才生效
???????????????????????????????????? //其中一個特例是,如果數據點的最小值為0,則min端不增長數軸,數據點會出現的邊框上
???????????????????????????????????? //對X軸,該值默認為null,對Y軸,該值默認為0.02
???
??? labelWidth: null or number
??? labelHeight: null or number
??? transform: null or fn: number -> number
??? inverseTransform: null or fn: number -> number
???
??? ticks: null or number or ticks array or (fn: range -> ticks array)
??? tickSize: number or array
??? minTickSize: number or array
??? tickFormatter: (fn: number, object -> string) or string
??? tickDecimals: null or number
? }
All axes have the same kind of options. The "mode" option
determines how the data is interpreted, the default of null means as
decimal numbers. Use "time" for time series data, see the next section.
所有數軸都有相同的參數設置,mode為null表示數軸十進制,為time設置為時間軸
The options "min"/"max" are the precise minimum/maximum value on the
scale. If you don't specify either of them, a value will automatically
be chosen based on the minimum/maximum data values.
"min"/"max" 設置數軸最大值和最小值,如果沒有明確指定他們,將自動使用數據中的最小值和最大值
The "autoscaleMargin" is a bit esoteric: it's the fraction of margin
that the scaling algorithm will add to avoid that the outermost points
ends up on the grid border. Note that this margin is only applied
when a min or max value is not explicitly set. If a margin is
specified, the plot will furthermore extend the axis end-point to the
nearest whole tick. The default value is "null" for the x axis and
0.02 for the y axis which seems appropriate for most cases.
"autoscaleMargin"的解釋見上文
"labelWidth" and "labelHeight" specifies a fixed size of the tick
labels in pixels. They're useful in case you need to align several
plots.
"labelWidth" 和 "labelHeight" 用于設置數軸刻度標簽的高寬,這個屬性在你需要排列整齊幾個圖表的時候會派上用場。
"transform" and "inverseTransform" are callbacks you can put in to
change the way the data is drawn. You can design a function to
compress or expand certain parts of the axis non-linearly, e.g.
suppress weekends or compress far away points with a logarithm or some
other means. When Flot draws the plot, each value is first put through
the transform function. Here's an example, the x axis can be turned
into a natural logarithm axis with the following code:
"transform" and "inverseTransform" 是回調函數,用于改變數軸上的數據顯示方式,
你可以設計一個函數來非線性地擴展或壓縮數軸上的特定數據段
? xaxis: {
??? transform: function (v) { return Math.log(v); },
??? inverseTransform: function (v) { return Math.exp(v); }
? }
Note that for finding extrema, Flot assumes that the transform
function does not reorder values (monotonicity is assumed).
需要注意的是,flot假定transform函數不會修改數據點的排列順序
The inverseTransform is simply the inverse of the transform function
(so v == inverseTransform(transform(v)) for all relevant v). It is
required for converting from canvas coordinates to data coordinates,
e.g. for a mouse interaction where a certain pixel is clicked. If you
don't use any interactive features of Flot, you may not need it.
inverseTransform 函數是對transform的逆運算,因此有:v == inverseTransform(transform(v)
當需要把坐標數據轉換回數值數據時就會用到這個函數,這常在圖表的動態交互時發生,比如鼠標在
圖標上面點擊并獲取該點數據,但是如果你不做任何動態的交互,你可能不會用到這個函數。
The rest of the options deal with the ticks.
其他與刻度的網格線有關的參數。
If you don't specify any ticks, a tick generator algorithm will make
some for you. The algorithm has two passes. It first estimates how
many ticks would be reasonable and uses this number to compute a nice
round tick interval size. Then it generates the ticks.
如果你沒有明確地設置刻度間隔,程序會自動設置,設置過程分為2步,
首先估計數軸刻度間隔所需數目,其次根據這個數目通過四舍五入方法估算合適的步長,最后生成刻度
You can specify how many ticks the algorithm aims for by setting
"ticks" to a number. The algorithm always tries to generate reasonably
round tick values so even if you ask for three ticks, you might get
five if that fits better with the rounding. If you don't want any
ticks at all, set "ticks" to 0 or an empty array.
通過設置"ticks" 的值為數字,你可以設置圖表產生刻度間隔的個數,但是程序盡量會設置最合適的刻度
個數,因此,盡管你設置了3個刻度數,卻可能得到5個,如果你不需要自己設置刻度,把"ticks"的值設置為0或一個空數組
Another option is to skip the rounding part and directly set the tick
interval size with "tickSize". If you set it to 2, you'll get ticks at
2, 4, 6, etc. Alternatively, you can specify that you just don't want
ticks at a size less than a specific tick size with "minTickSize".
Note that for time series, the format is an array like [2, "month"],
see the next section.
"tickSize"直接跳過估算步驟設置刻度間隔步長,如果你設置該值為2,生成的刻度將會是形如2,4,6
"minTickSize"可以設置刻度間隔的最小值,
If you want to completely override the tick algorithm, you can specify
an array for "ticks", either like this:
如果你想完全的自定義刻度,可以設置參數"ticks"的值為一個數組,賦值方法如下例:
? ticks: [0, 1.2, 2.4]
Or like this where the labels are also customized:
或者像下面的例子,連刻度的標簽也自定義:
? ticks: [[0, "zero"], [1.2, "one mark"], [2.4, "two marks"]]
You can mix the two if you like.
這兩種方法可以混合使用
?
For extra flexibility you can specify a function as the "ticks"
parameter. The function will be called with an object with the axis
min and max and should return a ticks array. Here's a simplistic tick
generator that spits out intervals of pi, suitable for use on the x
axis for trigonometric functions:
刻度可以用函數來生成,方法是把一個函數賦給"ticks",該函數應該以一個具有最大刻度值及最小刻度值的數軸對象為參數,
該函數返回一個刻度數組賦給"ticks"。
下例是一個簡單的刻度生成器,例子以pi值為刻度間隔大小,這對三角函數曲線非常適用。
? function piTickGenerator(axis) {
??? var res = [], i = Math.floor(axis.min / Math.PI);
??? do {
????? var v = i * Math.PI;
????? res.push([v, i + "\u03c0"]);
????? ++i;
??? } while (v < axis.max);
???
??? return res;
? }
You can control how the ticks look like with "tickDecimals", the
number of decimals to display (default is auto-detected).
"tickDecimals" 用于設置刻度的小數位數,默認情況下程序會自動判斷截取
Alternatively, for ultimate control over how ticks look like you can
provide a function to "tickFormatter". The function is passed two
parameters, the tick value and an "axis" object with information, and
should return a string. The default formatter looks like this:
"tickFormatter"可以通過函數來設置刻度顯示格式,格式函數有2個參數,刻度值及數軸對象。函數應該返回一個字符串賦給tickFormatter。
"tickFormatter"格式函數基本格式如下:
? function formatter(val, axis) {
??? return val.toFixed(axis.tickDecimals);
? }
The axis object has "min" and "max" with the range of the axis,
"tickDecimals" with the number of decimals to round the value to and
"tickSize" with the size of the interval between ticks as calculated
by the automatic axis scaling algorithm (or specified by you). Here's
an example of a custom formatter:
數軸對象可以獲取數軸數據的最大值和最小值,tickDecimals可以獲取刻度標簽的小數位數,
tickSize可以獲取刻度間隔長度(程序算法自動計算出或自定義)。
? function suffixFormatter(val, axis) {
??? if (val > 1000000)
????? return (val / 1000000).toFixed(axis.tickDecimals) + " MB";? // toFixed() 函數,把數值四舍五入為指定小數位數
??? else if (val > 1000)
????? return (val / 1000).toFixed(axis.tickDecimals) + " kB";
??? else
????? return val.toFixed(axis.tickDecimals) + " B";
? }
Time series data
時間數軸
================
Time series are a bit more difficult than scalar data because
calendars don't follow a simple base 10 system. For many cases, Flot
abstracts most of this away, but it can still be a bit difficult to
get the data into Flot. So we'll first discuss the data format.
時間數軸比標量數軸要難一點,因為時間數軸并不遵循10進制。下面討論時間數軸的數據格式
The time series support in Flot is based on Javascript timestamps,
i.e. everywhere a time value is expected or handed over, a Javascript
timestamp number is used. This is a number, not a Date object. A
Javascript timestamp is the number of milliseconds since January 1,
1970 00:00:00 UTC. This is almost the same as Unix timestamps, except it's
in milliseconds, so remember to multiply by 1000!
flot對時間軸的支持是基于javascript的時間戳的,也就是說每個已經過去的或未來的時間都對應一個時間戳。
時間戳是一個數字,不是時間對象。
javascript時間戳精確到毫秒,起始時間從通用協調時間(UTC)的1970年1月1日零時零分零秒開始,這幾乎跟unix時間戳一致,不同的是
javascript時間戳是以毫秒來計算的,因此如果使用unix時間戳的話不要忘記乘以1000.
You can see a timestamp like this
通過下面的例子可以查看一個時間的時間戳:
? alert((new Date()).getTime())
Normally you want the timestamps to be displayed according to a
certain time zone, usually the time zone in which the data has been
produced. However, Flot always displays timestamps according to UTC.
It has to as the only alternative with core Javascript is to interpret
the timestamps according to the time zone that the visitor is in,
which means that the ticks will shift unpredictably with the time zone
and daylight savings of each visitor.
你可能希望時間戳根據某一時區(通常是產生數據的時區)來顯示,但是,flot總是根據UTC時區來顯示時間戳,
因此你只能在javascript代碼里設置根據用戶本地時區來解釋時間戳,這意味著UTC時間戳按不同時區轉換之后處于不同時區的用戶看到的時間將不一樣
So given that there's no good support for custom time zones in
Javascript, you'll have to take care of this server-side.
如果客戶端的javascript對時區的支持不是很好的話,就要在服務器端小心的處理好數據了
The easiest way to think about it is to pretend that the data
production time zone is UTC, even if it isn't. So if you have a
datapoint at 2002-02-20 08:00, you can generate a timestamp for eight
o'clock UTC even if it really happened eight o'clock UTC+0200.
最簡單的方法是,不管數據產生地的時區是哪里,都假定為UTC,也就是說,如果有一個數據點
在2002-02-20 08:00產生,就算是在UTC+0200 時區8時產生的,你也要按UTC時區8時產生時間戳。
(做數據文件里保存UTC時間戳,實際在客戶端顯示時通過程序指定時區--通常是數據產生地所在時區--進行轉換)
In PHP you can get an appropriate timestamp with
'strtotime("2002-02-20 UTC") * 1000', in Python with
'calendar.timegm(datetime_object.timetuple()) * 1000', in .NET with
something like:
下面服務器端生成恰當的時間戳方法:
在PHP程序中? strtotime("2002-02-20 UTC") * 1000
Python中? calendar.timegm(datetime_object.timetuple()) * 1000
在 .net中代碼如下:
? public static int GetJavascriptTimestamp(System.DateTime input)
? {
??? System.TimeSpan span = new System.TimeSpan(System.DateTime.Parse("1/1/1970").Ticks);
??? System.DateTime time = input.Subtract(span);
??? return (long)(time.Ticks / 10000);
? }
Javascript also has some support for parsing date strings, so it is
possible to generate the timestamps manually client-side.
javascript 也有一些對時間字符串進行解析的支持,因此在客戶端生成時間戳也是可能的。
If you've already got the real UTC timestamp, it's too late to use the
pretend trick described above. But you can fix up the timestamps by
adding the time zone offset, e.g. for UTC+0200 you would add 2 hours
to the UTC timestamp you got. Then it'll look right on the plot. Most
programming environments have some means of getting the timezone
offset for a specific date (note that you need to get the offset for
each individual timestamp to account for daylight savings).
如果你得到的時間數據已經是數據產生時對應時區的時間戳,使用上面的方法已經來不及了,
不過你可以通過增加時區偏移的方法修改時間戳。例如,你得到一個UTC+0200時區(比UTC時區快2小時)
的時間戳,那么你需要在這個時間戳上減去2小時(或者說加上UTC時間對本地區時間的時差-2小時),這樣在圖表上看起來時間就正確了,
很多編程環境都有專門用于計算時差的方法,需要注意的是,你需要為每個時間戳計算時差來解釋日光節約時間(歐美在夏天天亮較早的季節使用的一個時間計算法,
人為地把時間撥快一小時,促使人早起早睡,節約用電)
Once you've gotten the timestamps into the data and specified "time"
as the axis mode, Flot will automatically generate relevant ticks and
format them. As always, you can tweak the ticks via the "ticks" option
- just remember that the values should be timestamps (numbers), not
Date objects.
一旦你在數據里面使用時間戳并把數軸設置為時間模式,flot會自動格式化并生成時間數軸刻度。
你也可以通過"ticks"參數來自定義時間刻度,但是要注意的是,對應的參數值應該是時間戳數字而不是時間對象。
Tick generation and formatting can also be controlled separately
through the following axis options:
通過設置下面的數軸參數可以個別的控制時間軸刻度生成的格式:
? minTickSize: array
? timeformat: null or format string //null 或格式化字符串
? monthNames: null or array of size 12 of strings //null或一個長度為12的字符串數組
? twelveHourClock: boolean?? //12時模式
Here "timeformat" is a format string to use. You might use it like this:
timeformat的用法如下例:
? xaxis: {
??? mode: "time"
??? timeformat: "%y/%m/%d"
? }
?
This will result in tick labels like "2000/12/24". The following
specifiers are supported
這個例子產生的時間抽刻度標簽形如"2000/12/24" ,下面是flot支持的時間格式化字符串:
? %h: hours
? %H: hours (left-padded with a zero)
? %M: minutes (left-padded with a zero)
? %S: seconds (left-padded with a zero)
? %d: day of month (1-31)
? %m: month (1-12)
? %y: year (four digits)
? %b: month name (customizable)
? %p: am/pm, additionally switches %h/%H to 12 hour instead of 24
? %P: AM/PM (uppercase version of %p)
You can customize the month names with the "monthNames" option. For
instance, for Danish you might specify:
"monthNames" 參數自定義月份名稱的方法如下:
? monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
If you set "twelveHourClock" to true, the autogenerated timestamps
will use 12 hour AM/PM timestamps instead of 24 hour.
?
"twelveHourClock"設置為true,將使用12時AM/PM 格式的時間戳來替代24時時間戳。
The format string and month names are used by a very simple built-in
format function that takes a date object, a format string (and
optionally an array of month names) and returns the formatted string.
If needed, you can access it as $.plot.formatDate(date, formatstring,
monthNames) or even replace it with another more advanced function
from a date library if you're feeling adventurous.
格式化字符串和月份名稱經常用在格式化函數中,該函數可能使用時間對象,格式化字符串,月份名稱數組作為參數,
返回格式化了的字符串,如果需要,你可以使用flot提供的方法 $.plot.formatDate(date, formatstring,monthNames)
也可以自定義函數來替換該方法。
If everything else fails, you can control the formatting by specifying
a custom tick formatter function as usual. Here's a simple example
which will format December 24 as 24/12:
如果以上方法格式化不能達到你的要求,你可以定義一個函數來格式化并自定義刻度標簽。
? tickFormatter: function (val, axis) {
??? var d = new Date(val);
??? return d.getUTCDate() + "/" + (d.getUTCMonth() + 1);
? }
Note that for the time mode "tickSize" and "minTickSize" are a bit
special in that they are arrays on the form "[value, unit]" where unit
is one of "second", "minute", "hour", "day", "month" and "year". So
you can specify
請注意,時間軸的"tickSize" 和 "minTickSize"是一個數組,數組形如 [數值,單位],
單位可以是 "second", "minute", "hour", "day", "month" and "year" ,因此你可以這樣設置最小刻度為一個月:
? minTickSize: [1, "month"]
to get a tick interval size of at least 1 month and correspondingly,
if axis.tickSize is [2, "day"] in the tick formatter, the ticks have
been produced with two days in-between.
類似地,axis.tickSize設置為[2, "day"],則時間軸最小刻度為2天。
Customizing the data series
數據顯示定制
===========================
? series: {
??? lines, points, bars: {
????? show: boolean
????? lineWidth: number
????? fill: boolean or number
????? fillColor: null or color/gradient
??? }
??? points: {
????? radius: number
??? }
??? bars: {
????? barWidth: number
????? align: "left" or "center"
????? horizontal: boolean
??? }
??? lines: {
????? steps: boolean
??? }
??? shadowSize: number
? }
?
? colors: [ color1, color2, ... ]
The options inside "series: {}" are copied to each of the series. So
you can specify that all series should have bars by putting it in the
global options, or override it for individual series by specifying
bars in a particular the series object in the array of data.
"series: {}" 內的參數將對每一個數據序列生效,可以用來為圖表設置全局參數,
如果需要為特定數據序列的圖表設置不同屬性,可以在對應的數據序列對象里面設置相應的參數把全局參數覆蓋掉。
?
The most important options are "lines", "points" and "bars" that
specify whether and how lines, points and bars should be shown for
each data series. In case you don't specify anything at all, Flot will
default to showing lines (you can turn this off with
lines: { show: false}). You can specify the various types
independently of each other, and Flot will happily draw each of them
in turn (this is probably only useful for lines and points), e.g.
?"lines", "points" 和 "bars"是最重要的參數,這些參數設置每條數據序列的圖表的折線圖、散點圖、直方圖是否顯示和如何顯示。
如果沒有專門設置這三個參數中的任何一個,默認情況下將顯示折線圖,關閉折線圖的方法是lines: { show: false}
你可以分別設置這三種顯示方式,flot會一次把它們全部顯示出來(通常情況下折線圖和散點圖同時顯示比較有意義),如下例:
? var options = {
??? series: {
????? lines: { show: true, fill: true, fillColor: "rgba(255, 255, 255, 0.8)" },
????? points: { show: true, fill: false }
??? }
? };
"lineWidth" is the thickness of the line or outline in pixels. You can
set it to 0 to prevent a line or outline from being drawn; this will
also hide the shadow.
"lineWidth"用于設置折線圖線條的粗細或其他圖型的邊框,你可以把這個值設置成0來關閉折線圖的輸出
或關閉其他圖形的邊框及陰影效果(例如散點圖的鼠標點擊效果及直方圖的邊框效果)
"fill" is whether the shape should be filled. For lines, this produces
area graphs. You can use "fillColor" to specify the color of the fill.
If "fillColor" evaluates to false (default for everything except
points which are filled with white), the fill color is auto-set to the
color of the data series. You can adjust the opacity of the fill by
setting fill to a number between 0 (fully transparent) and 1 (fully
opaque).
"fill" 用于設置圖表填充的透明度(0-1),對于折線,填充范圍是折線與數軸圍成的區域
"fillColor" 設置填充顏色,如果填null,將使用線條顏色一致的顏色,如果顏色名解析失敗將使用默認顏色(折線圖直方圖黑色,散點圖白色)
For bars, fillColor can be a gradient, see the gradient documentation
below. "barWidth" is the width of the bars in units of the x axis (or
the y axis if "horizontal" is true), contrary to most other measures
that are specified in pixels. For instance, for time series the unit
is milliseconds so 24 * 60 * 60 * 1000 produces bars with the width of
a day. "align" specifies whether a bar should be left-aligned
(default) or centered on top of the value it represents. When
"horizontal" is on, the bars are drawn horizontally, i.e. from the y
axis instead of the x axis; note that the bar end points are still
defined in the same way so you'll probably want to swap the
coordinates if you've been plotting vertical bars first.
直方圖的填充顏色可以是漸變的,關于漸變的說明在后面會提及。
"barWidth" 用于設置直方圖的寬度,單位是數軸的單位而非像素。
例如,時間軸的單位是毫秒,因此,barWidth的值設置為24 * 60 * 60 * 1000 表示直方圖的寬度是一天時間的在時間軸上的長度。
"align" 用于設置數據點對應刻度線與直方圖之間的對齊關系,默認情況下,刻度線在直方圖的左側(left,靠近數軸最小值一側),
如果設置為center,刻度線在直方圖中間。
For lines, "steps" specifies whether two adjacent data points are
connected with a straight (possibly diagonal) line or with first a
horizontal and then a vertical line. Note that this transforms the
data by adding extra points.
對于折線圖,"steps"可以設置是否使用階梯狀折線,設置為true采用階梯狀折線,相鄰2個數據點之間先以水平線連接,
后然用垂直線連接,需要注意的是,這種模式會在同一垂直線上增加數據點來實現。
"shadowSize" is the default size of shadows in pixels. Set it to 0 to
remove shadows.
"shadowSize" 可以設置曲線陰影大小,設置為0關閉陰影效果。
The "colors" array specifies a default color theme to get colors for
the data series from. You can specify as many colors as you like, like
this:
"colors"可以預定義一系列顏色保存在數組里供曲線使用,你可以設置任意多種顏色。
? colors: ["#d18b2c", "#dba255", "#919733"]
If there are more data series than colors, Flot will try to generate
extra colors by lightening and darkening colors in the theme.
如果曲線的數目比預定義的顏色數目多,程序將嘗試通過改變顏色的明暗程度來生成其他顏色賦給曲線。
Customizing the grid
背景柵格定制
====================
? grid: {
??? show: boolean
??? aboveData: boolean
??? color: color
??? backgroundColor: color/gradient or null
??? tickColor: color
??? labelMargin: number
??? markings: array of markings or (fn: axes -> array of markings)
??? borderWidth: number
??? borderColor: color or null
??? clickable: boolean
??? hoverable: boolean
??? autoHighlight: boolean
??? mouseActiveRadius: number
? }
The grid is the thing with the axes and a number of ticks. "color" is
the color of the grid itself whereas "backgroundColor" specifies the
background color inside the grid area. The default value of null means
that the background is transparent. You can also set a gradient, see
the gradient documentation below.
grid由數軸和刻度線構成的柵格背景,"color"定義的是grid的顏色,包括刻度值標簽的顏色。
但是背景顏色是填充在Grid里面的,因此實際上只影響邊框和刻度值標簽的顏色。
背景顏色"backgroundColor"是填充在grid內部的,默認情況下背景是透明的,
可以為背景設置顏色漸變,具體細節后面會提到。
You can turn off the whole grid including tick labels by setting
"show" to false. "aboveData" determines whether the grid is drawn on
above the data or below (below is default).
如果grid的"show"參數設置為false,柵格背景包括數軸及數軸刻度標簽將被隱藏,
"aboveData" 用于設置柵格放置在數據點上面還是下面,默認情況false是放在數據點下面。
"aboveData"設置為true且設置了背景顏色,曲線將被grid的背景顏色遮蓋。
"tickColor" is the color of the ticks and "labelMargin" is the spacing
between tick labels and the grid. Note that you can style the tick
labels with CSS, e.g. to change the color. They have class "tickLabel".
"borderWidth" is the width of the border around the plot. Set it to 0
to disable the border. You can also set "borderColor" if you want the
border to have a different color than the grid lines.
"tickColor"?? 設置刻度線的顏色
"labelMargin" 設置刻度值標簽與網格的距離,
"borderWidth" 設置邊框寬度,設為0則取消邊框
"borderColor" 設置邊框顏色,
"tickLabel"?? 設置刻度值標簽的CSS樣式,(未實驗,設置方法不明)
"markings" is used to draw simple lines and rectangular areas in the
background of the plot. You can either specify an array of ranges on
the form { xaxis: { from, to }, yaxis: { from, to } } (secondary axis
coordinates with x2axis/y2axis) or with a function that returns such
an array given the axes for the plot in an object as the first
parameter.
You can set the color of markings by specifying "color" in the ranges
object. Here's an example array:
"markings" 用于在背景上繪畫出一塊矩形,矩形的位置及長寬通過縱橫軸的起始終止坐標來確定,
第一橫軸與第一縱軸對應,第二橫軸與第二縱軸對應,color參數可以設置畫出區塊的顏色,
賦值方式是一個數組,每個數組元素是一個json數據格式,每個數組元素繪制一個區塊。可以用函數返回數組來賦值。
下面是個簡單例子:
? markings: [ { xaxis: { from: 0, to: 2 }, yaxis: { from: 10, to: 10 }, color: "#bb0000" }, ... ]
If you leave out one of the values, that value is assumed to go to the
border of the plot. So for example if you only specify { xaxis: {
from: 0, to: 2 } } it means an area that extends from the top to the
bottom of the plot in the x range 0-2.
A line is drawn if from and to are the same, e.g.
? markings: [ { yaxis: { from: 1, to: 1 } }, ... ]
would draw a line parallel to the x axis at y = 1. You can control the
line width with "lineWidth" in the range object.
如果只設置一個數軸的數據范圍,則缺省數軸的數據范圍默認為[min,max],
如果數軸起止值相等,則畫出一條線,并且可以使用"lineWidth"設定線段的大小。
An example function might look like this:
? markings: function (axes) {
??? var markings = [];
??? for (var x = Math.floor(axes.xaxis.min); x < axes.xaxis.max; x += 2)
????? markings.push({ xaxis: { from: x, to: x + 1 } });
??? return markings;
? }
If you set "clickable" to true, the plot will listen for click events
on the plot area and fire a "plotclick" event on the placeholder with
a position and a nearby data item object as parameters. The coordinates
are available both in the unit of the axes (not in pixels) and in
global screen coordinates.
"clickable" 設置為true時,圖表將監聽鼠標單擊事件,單擊圖表時將觸發"plotclick"事件,
回調函數的參數是鼠標坐標和數據點的坐標值,即以像素為單位的位置坐標及以數軸為單位的數據坐標。
如果鼠標點擊位置沒有數據點,則數據點的參數值是null,反之,是一個json對象
Likewise, if you set "hoverable" to true, the plot will listen for
mouse move events on the plot area and fire a "plothover" event with
the same parameters as the "plotclick" event. If "autoHighlight" is
true (the default), nearby data items are highlighted automatically.
If needed, you can disable highlighting and control it yourself with
the highlight/unhighlight plot methods described elsewhere.
同樣地,"hoverable" 設置為true將監聽鼠標移動事件,鼠標移動到某個位置時發生"plothover"事件,
回調函數的參數與"clickable"一致,
"autoHighlight"的值為true,則發生"hoverable"事件和"plotclick"事件時,數據點顯示高亮效果,
數據點高亮的發生及消失對應有highlight/unhighlight方法,這在后面會描述。
You can use "plotclick" and "plothover" events like this:
"plotclick" 和 "plothover" 事件用法如下:
??? $.plot($("#placeholder"), [ d ], { grid: { clickable: true } });
??? $("#placeholder").bind("plotclick", function (event, pos, item) {
??????? alert("You clicked at " + pos.x + ", " + pos.y);?????????????????
??????? // secondary axis coordinates if present are in pos.x2, pos.y2,???????? //pos.x pos.y 數軸坐標值,pos.x2, pos.y2 第二對數軸的坐標值
??????? // if you need global screen coordinates, they are pos.pageX, pos.pageY //pos.pageX, pos.pageY 屏幕坐標值
??????? if (item) {??? //item !=null ,點擊了數據點
????????? highlight(item.series, item.datapoint);? // item.datapoint 該數據點的縱橫坐標值,是一對以逗號分割的數值 如: 3.5,2.14 表示該點X軸的值為3.5,Y軸的值為2.14
????????? alert("You clicked a point!");?????????? //注意,item.datapoint的值不一定與 pos.x pos.y的值相等,因為點擊在數據點附近,數據點也激活了
??????? }
??? });
The item object in this example is either null or a nearby object on the form:
? item: {?? //item參數的屬性
????? datapoint: the point, e.g. [0, 2]
????? dataIndex: the index of the point in the data array? //該點數據在對應數列數組里的下標
????? series: the series object //曲線對象
????? seriesIndex: the index of the series? //在多曲線體系中該曲線的下標,即第幾條曲線,編號從0開始
????? pageX, pageY: the global screen coordinates of the point? //該點屏幕坐標,單位是像素
? }
For instance, if you have specified the data like this
? 下面是一條曲線的定義,
??? $.plot($("#placeholder"), [ { label: "Foo", data: [[0, 10], [7, 3]] } ], ...);
and the mouse is near the point (7, 3), "datapoint" is [7, 3],
"dataIndex" will be 1, "series" is a normalized series object with
among other things the "Foo" label in series.label and the color in
series.color, and "seriesIndex" is 0. Note that plugins and options
that transform the data can shift the indexes from what you specified
in the original data array.
鼠標的(7,3)坐標附近觸發事件時,"datapoint" 的值是[7,3],
item.datapoint=="7,3"
item.dataIndex ==1
item.seriesIndex == 0?
item.series 曲線對象,
item.series.label =="Foo" 曲線名稱
item.series.color 曲線顏色,rgb格式
If you use the above events to update some other information and want
to clear out that info in case the mouse goes away, you'll probably
also need to listen to "mouseout" events on the placeholder div.
如果你在以上事件觸發時修改數據點的一些值,鼠標移開時想復原這些值,你很可能就需要在占位符上監聽鼠標移開事件
"mouseActiveRadius" specifies how far the mouse can be from an item
and still activate it. If there are two or more points within this
radius, Flot chooses the closest item. For bars, the top-most bar
(from the latest specified data series) is chosen.
"mouseActiveRadius" 用來設置可以激活數據點的鼠標與數據點之間的距離,如果在符合距離內有多個數據點,flot會激活最近的數據點
對于直方圖,則激活最遲設置的直方圖。
If you want to disable interactivity for a specific data series, you
can set "hoverable" and "clickable" to false in the options for that
series, like this { data: [...], label: "Foo", clickable: false }.
在某條曲線數據本身設置"hoverable" 和 "clickable" 為false則該曲線不會觸發事件
但options內設置為false時,不能在某條曲線內通過設置true來開啟事件監聽功能
Specifying gradients
定義變化模式
====================
A gradient is specified like this:
曲線顏色預定義:
? { colors: [ color1, color2, ... ] }
For instance, you might specify a background on the grid going from
black to gray like this:
圖表柵格背景顏色漸變:
? grid: {
??? backgroundColor: { colors: ["#000", "#999"] }
? }
For the series you can specify the gradient as an object that
specifies the scaling of the brightness and the opacity of the series
color, e.g.
曲線顏色明暗程度及透明度漸變設置,包括開始狀態和結束狀態的數據(實驗不成功):
? { colors: [{ opacity: 0.8 }, { brightness: 0.6, opacity: 0.8 } ] }
where the first color simply has its alpha scaled, whereas the second
is also darkened. For instance, for bars the following makes the bars
gradually disappear, without outline:
如下例,第一條直方圖明度正常,但是后面的逐漸變暗,最后消失:
? bars: {
????? show: true,
????? lineWidth: 0,
????? fill: true,
????? fillColor: { colors: [ { opacity: 0.8 }, { opacity: 0.1 } ] }
? }
?
Flot currently only supports vertical gradients drawn from top to
bottom because that's what works with IE.
flot目前只支持從圖表top到bottom的垂直漸變,因為IE只能這樣實現漸變
Plot Methods
方法
------------
The Plot object returned from the plot function has some methods you
can call:
plot函數返回的對象有下面一些方法可供調用:
? - highlight(series, datapoint)? //激活數據點 series:曲線編號,datapoint:數據點在曲線數據序列中的編號,編號都是從0開始 例如:highlight(1, 1) 激活第二條曲線的第二個數據點
????????????????????????????????? //datapoint 也可以是一個數據點的真實數據對象,是一個數組, 例如: highlight(1, [3,6]) 激活第二條曲線上坐標為[3,6]的點
????????????????????????????????? //如果指定坐標的數據點不在該曲線上,仍然以該曲線的顏色顯示要激活的數據點
??? Highlight a specific datapoint in the data series. You can either
??? specify the actual objects, e.g. if you got them from a
??? "plotclick" event, or you can specify the indices, e.g.
??? highlight(1, 3) to highlight the fourth point in the second series
??? (remember, zero-based indexing).
?
? - unhighlight(series, datapoint) or unhighlight() //取消數據點的激活效果,參數與highlight相同
??? Remove the highlighting of the point, same parameters as
??? highlight.
??? If you call unhighlight with no parameters, e.g. as
??? plot.unhighlight(), all current highlights are removed.? //如果unhighlight()沒有設置參數,取消所有數據點的激活狀態
? - setData(data)
??? You can use this to reset the data used. Note that axis scaling,
??? ticks, legend etc. will not be recomputed (use setupGrid() to do
??? that). You'll probably want to call draw() afterwards.
??? 重新設置曲線數據,參數data是plot(placeholder, data, options)中的data參數,可以不包含options的設置內容。
??? 重新設置數據后,如果需要立即改變圖表顯示,請調用draw()方法來重新繪制圖表
??? 請注意,setData()方法并不會重新設置數軸的縮放比例、刻度、曲線名稱等,如果需要修改這些屬性,請使用setupGrid()方法,
??? You can use this function to speed up redrawing a small plot if
??? you know that the axes won't change. Put in the new data with
??? setData(newdata), call draw(), and you're good to go. Note that
??? for large datasets, almost all the time is consumed in draw()
??? plotting the data so in this case don't bother.
??? 如果你預先知道重新設置數據后數軸不需要改變,可以用setData(data)來設置數據然后調用draw()快速重繪曲線
??? 如果數據量比較大,draw()方法可能會消耗較長時間,因此可能會有一點延遲,請不必感到疑惑。
???
? - setupGrid()
??? Recalculate and set axis scaling, ticks, legend etc.
??
?? 修改數軸、刻度、曲線名稱等,參數是 options 不包括data部分
??? Note that because of the drawing model of the canvas, this
??? function will immediately redraw (actually reinsert in the DOM)
??? the labels and the legend, but not the actual tick lines because
??? they're drawn on the canvas. You need to call draw() to get the
??? canvas redrawn.
???
??? 請注意,該方法不會重繪曲線就立即修改刻度標簽及曲線名稱,因為這些屬性是以DOM節點的形式來實現的
??? 在canvas標簽內實現的屬性,比如刻度線,你需要調用draw()方法來重繪在canvas標簽內實現的屬性。
??? 應該注意,如果原來圖表上沒有的數軸,在setupGrid()設置之后出現該數軸,那么 該數軸會疊在Grid上,
? - draw()
??? Redraws the plot canvas.? //重繪圖表的canvas
? - triggerRedrawOverlay()
??? Schedules an update of an overlay canvas used for drawing
??? interactive things like a selection and point highlights. This
??? is mostly useful for writing plugins. The redraw doesn't happen
??? immediately, instead a timer is set to catch multiple successive
??? redraws (e.g. from a mousemove).
??? 添加一個覆蓋在圖標上的canvas,這個方法對圖表插件的開發非常有用,特別是一些動態的交互性的設置
??? 比如彈出一個下拉菜單或增加一個亮點。
??? 這個方法不會立即繪制設置的canvas內容,繪制的時機可以通過設置延時或鼠標事件來觸發。
? - width()/height()
??? Gets the width and height of the plotting area inside the grid.
??? This is smaller than the canvas or placeholder dimensions as some
??? extra space is needed (e.g. for labels).
??? 獲取圖表柵格的寬和高,寬高值會比canvas和占位符的尺寸小。
? - offset()
??? Returns the offset of the plotting area inside the grid relative
??? to the document, useful for instance for calculating mouse
??? positions (event.pageX/Y minus this offset is the pixel position
??? inside the plot).
??
?? 獲取圖表的繪制區相對文檔的坐標,鼠標事件觸發獲取的文檔坐標減去該坐標將得到當前位置相對于繪圖區的位置偏移。
?? offset().left , offset().top 獲取左偏移和頂部偏移
???
? - pointOffset({ x: xpos, y: ypos })
??? Returns the calculated offset of the data point at (x, y) in data
??? space within the placeholder div. If you are working with dual axes, you
??? can specify the x and y axis references, e.g.
?? 獲取某個數據點位置相對于占位符的偏移。注意,不是相對canvas,而是相對于DIV
?? 可以為數據點的值注明采用的數軸,默認采用第一坐標系。
?? pointOffset({ x: 3, y: 3.5 }).left? pointOffset({ x: 3, y: 3.5 }).top? 分別是數據點(3,3.5)位置相對于容器DIV的偏移
???
????? o = pointOffset({ x: xpos, y: ypos, xaxis: 2, yaxis: 2 })
????? // o.left and o.top now contains the offset within the div
?
There are also some members that let you peek inside the internal
workings of Flot which is useful in some cases. Note that if you change
something in the objects returned, you're changing the objects used by
Flot to keep track of its state, so be careful.
? 下面是一些獲取圖表相關屬性的方法,
? - getData()
??? Returns an array of the data series currently used in normalized
??? form with missing settings filled in according to the global
??? options. So for instance to find out what color Flot has assigned
??? to the data series, you could do this:
??? 獲取plot(placeholder, data, options) 函數的data 和 options 合成的數據,
??? getData() 并非僅僅返回函數的 data 參數,他是一個數組,里面的信息包含了這個曲線的信息,
??? 包括options,每一條曲線的每一個參數設置、包括默認設置的值及格式函數
??? 注意與setData()的參數區別,oo.setData(data), 則 data!= oo.getData()
????? var series = plot.getData();
????? for (var i = 0; i < series.length; ++i)
??????? alert(series[i].color);?? //逐個彈出曲線的顏色
??? A notable other interesting field besides color is datapoints
??? which has a field "points" with the normalized data points in a
??? flat array (the field "pointsize" is the increment in the flat
??? array to get to the next point so for a dataset consisting only of
??? (x,y) pairs it would be 2).
? - getAxes()
??? Gets an object with the axes settings as { xaxis, yaxis, x2axis,
??? y2axis }.
??? 該方法返回數軸信息的json對象,該對象有四個成員,分別為xaxis, yaxis, x2axis, y2axis 四條數軸
??? Various things are stuffed inside an axis object, e.g. you could
??? use getAxes().xaxis.ticks to find out what the ticks are for the
??? xaxis. Two other useful attributes are p2c and c2p, functions for
??? transforming from data point space to the canvas plot space and
??? back. Both returns values that are offset with the plot offset.
???
??? 數軸內部包含了各種信息(具體信息可以把json對象轉化成字符串細看,這里不細述,本文后面有將json對象系列化成字符串的方法)
??? 例如獲取X軸第一個刻度標簽: getAxes().xaxis.ticks[0].label
??? 【c2p p2c兩個函數是用于計算并返回數據點與數軸直接的偏移量(包含曲線偏移量)】 看不太明白,待證實
?
? - getPlaceholder()
??? Returns placeholder that the plot was put into. This can be useful
??? for plugins for adding DOM elements or firing events.
???
??? 獲取圖表容器div,返回的是一個json對象
??? getPlaceholder().selector 返回該容器的jQuery選擇器,即 '#' + id
? - getCanvas()
??? Returns the canvas used for drawing in case you need to hack on it
??? yourself. You'll probably need to get the plot offset too.
?
?? 獲取繪制區canvas,返回的是一個json對象
?
? - getPlotOffset()
??? Gets the offset that the grid has within the canvas as an object
??? with distances from the canvas edges as "left", "right", "top",
??? "bottom". I.e., if you draw a circle on the canvas with the center
??? placed at (left, top), its center will be at the top-most, left
??? corner of the grid.
?? 獲取柵格邊緣與canvas邊緣之間的距離,有數軸的一邊間隔會大一些,因為需要縮小柵格防止數軸疊加在柵格上。
?? 該方法返回一個json對象,形如 {left:36,right:6,top:6,bottom:20}
? - getOptions()
??? Gets the options for the plot, in a normalized format with default
??? values filled in.
??? 獲取繪制函數的options參數,返回的是一個json對象
???
Hooks
事件鉤子
====================================================
In addition to the public methods, the Plot object also has some hooks
that can be used to modify the plotting process. You can install a
callback function at various points in the process, the function then
gets access to the internal data structures in Flot.
除了各種方法,flot還提供一些事件鉤子,你可以在圖表繪制過程中為事件鉤子設置回調函數以
修改圖表繪制過程,這些回調函數具備使用flot內部數據結構的權限。
Here's an overview of the phases Flot goes through:
下面是flot繪圖的步驟:
? 1. Plugin initialization, parsing options? //初始化引入的插件(如果有的話)設置,解析options的參數設置
?
? 2. Constructing the canvases used for drawing //創建canvas標簽
? 3. Set data: parsing data specification, calculating colors,???
???? copying raw data points into internal format,
???? normalizing them, finding max/min for axis auto-scaling
??????? //設置數據:解析數據設定,確定曲線顏色,把原始數據點的數據格式化成曲線所用格式,確定數軸的長度及縮放比例
? 4. Grid setup: calculating axis spacing, ticks, inserting tick
???? labels, the legend
?????? //柵格設定:計算數軸刻度及刻度標簽,設置曲線名稱
? 5. Draw: drawing the grid, drawing each of the series in turn
????? //畫圖:畫出柵格及曲線
? 6. Setting up event handling for interactive features
???? //設置用于交互的監聽事件函數
? 7. Responding to events, if any
???? //如果存在的話,觸發事件
Each hook is simply a function which is put in the appropriate array.
You can add them through the "hooks" option, and they are also available
after the plot is constructed as the "hooks" attribute on the returned
plot object, e.g.
事件鉤子是一些函數,這些函數被保存在一個數組里面,你可以通過指定事件鉤子數組的下標來添加和調用它們,
這些事件鉤子作為圖表"hooks"的屬性在圖表構造完畢后仍可以調用。
? // define a simple draw hook
? function hellohook(plot, canvascontext) { alert("hello!"); };
? // pass it in, in an array since we might want to specify several
? var plot = $.plot(placeholder, data, { hooks: { draw: [hellohook] } });
? // we can now find it again in plot.hooks.draw[0] unless a plugin
? // has added other hooks
The available hooks are described below. All hook callbacks get the
plot object as first parameter. You can find some examples of defined
hooks in the plugins bundled with Flot.
?事件鉤子函數的第一個參數是圖表對象
?- processOptions? [phase 1]
?? function(plot, options)
??
?? Called after Flot has parsed and merged options. Useful in the
?? instance where customizations beyond simple merging of default
?? values is needed. A plugin might use it to detect that it has been
?? enabled and then turn on or off other options.
??
?? processOptions發生在步驟1,圖表函數中產地options參數之后開始調用的函數,常用來修改options內的參數值
?
?- processRawData? [phase 3]
?? function(plot, series, data, datapoints)
?
?? Called before Flot copies and normalizes the raw data for the given
?? series. If the function fills in datapoints.points with normalized
?? points and sets datapoints.pointsize to the size of the points,
?? Flot will skip the copying/normalization step for this series.
??
?? processRawData發生在步驟3,曲線原始數據實例化之前調用,如果函數中的datapoints不為空,
??
??
?? In any case, you might be interested in setting datapoints.format,
?? an array of objects for specifying how a point is normalized and
?? how it interferes with axis scaling.
?? The default format array for points is something along the lines of:
???? [
?????? { x: true, number: true, required: true },
?????? { y: true, number: true, required: true }
???? ]
?? The first object means that for the first coordinate it should be
?? taken into account when scaling the x axis, that it must be a
?? number, and that it is required - so if it is null or cannot be
?? converted to a number, the whole point will be zeroed out with
?? nulls. Beyond these you can also specify "defaultValue", a value to
?? use if the coordinate is null. This is for instance handy for bars
?? where one can omit the third coordinate (the bottom of the bar)
?? which then defaults to 0.
?- processDatapoints? [phase 3]
?? function(plot, series, datapoints)
?
?? Called after normalization of the given series but before finding
?? min/max of the data points. This hook is useful for implementing data
?? transformations. "datapoints" contains the normalized data points in
?? a flat array as datapoints.points with the size of a single point
?? given in datapoints.pointsize. Here's a simple transform that
?? multiplies all y coordinates by 2:
???? function multiply(plot, series, datapoints) {
???????? var points = datapoints.points, ps = datapoints.pointsize;
???????? for (var i = 0; i < points.length; i += ps)
???????????? points[i + 1] *= 2;
???? }
?? Note that you must leave datapoints in a good condition as Flot
?? doesn't check it or do any normalization on it afterwards.
?- draw? [phase 5]
?? function(plot, canvascontext)
?
?? Hook for drawing on the canvas. Called after the grid is drawn
?? (unless it's disabled) and the series have been plotted (in case
?? any points, lines or bars have been turned on). For examples of how
?? to draw things, look at the source code.
??
?
?- bindEvents? [phase 6]
?? function(plot, eventHolder)
?? Called after Flot has setup its event handlers. Should set any
?? necessary event handlers on eventHolder, a jQuery object with the
?? canvas, e.g.
???? function (plot, eventHolder) {
???????? eventHolder.mousedown(function (e) {
???????????? alert("You pressed the mouse at " + e.pageX + " " + e.pageY);
???????? });
???? }
?? Interesting events include click, mousemove, mouseup/down. You can
?? use all jQuery events. Usually, the event handlers will update the
?? state by drawing something (add a drawOverlay hook and call
?? triggerRedrawOverlay) or firing an externally visible event for
?? user code. See the crosshair plugin for an example.
????
?? Currently, eventHolder actually contains both the static canvas
?? used for the plot itself and the overlay canvas used for
?? interactive features because some versions of IE get the stacking
?? order wrong. The hook only gets one event, though (either for the
?? overlay or for the static canvas).
?- drawOverlay? [phase 7]
?? function (plot, canvascontext)
?? The drawOverlay hook is used for interactive things that need a
?? canvas to draw on. The model currently used by Flot works the way
?? that an extra overlay canvas is positioned on top of the static
?? canvas. This overlay is cleared and then completely redrawn
?? whenever something interesting happens. This hook is called when
?? the overlay canvas is to be redrawn.
?? "canvascontext" is the 2D context of the overlay canvas. You can
?? use this to draw things. You'll most likely need some of the
?? metrics computed by Flot, e.g. plot.width()/plot.height(). See the
?? crosshair plugin for an example.
??
Plugins
插件
-------
Plugins extend the functionality of Flot. To use a plugin, simply
include its Javascript file after Flot in the HTML page.
If you're worried about download size/latency, you can concatenate all
the plugins you use, and Flot itself for that matter, into one big file
(make sure you get the order right), then optionally run it through a
Javascript minifier such as YUI Compressor.
Here's a brief explanation of how the plugin plumbings work:
Each plugin registers itself in the global array $.plot.plugins. When
you make a new plot object with $.plot, Flot goes through this array
calling the "init" function of each plugin and merging default options
from its "option" attribute. The init function gets a reference to the
plot object created and uses this to register hooks and add new public
methods if needed.
See the PLUGINS.txt file for details on how to write a plugin. As the
above description hints, it's actually pretty easy.
//========補充================
關于框選
數軸開啟選擇模式后,可綁定選擇事件
?$("#placeholder").bind("plotselected", function (event, ranges){ //doSomething??? })
其中ranges參數記錄了選擇曲線的區域,是一個json 對象,內容是各個數軸的選中區域起止點的值,形如:
{
"xaxis":{"from":2.286764705882353,"to":2.801470588235294},
"yaxis":{"from":0.6259124644481346,"to":7.250000055689011},
"y2axis":{"from":0.8345499525975129,"to":9.66666674091868}
}
?plot.setSelection(ranges,true) 方法,按ranges指定范圍設置選中區域,
??????????????? 如果沒有忽略true參數,曲線不重繪,只把選中區域顏色加深,曲線重繪并不會增加數據點,除非刷新使用的數據項
========================把json對象轉化成字符串==================================
<script type="text/javascript">
var JsonStr = function(JsonStrObj){
??? this.objType = (typeof JsonStrObj);
??? this.self = [];
??? (function(s,o){for(var i in o){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+JsonStrObj):JsonStrObj);
}
JsonStr.prototype = {
??? toString:function(){
??????? return this.getString();
??? },
??? valueOf:function(){
??????? return this.getString();
??? },
??? getString:function(){
??????? var sA = [];
??????? (function(o){
??????????? var oo = null;
??????????? sA.push('{');
??????????? for(var i in o){
??????????????? if(o.hasOwnProperty(i) && i!='prototype'){
??????????????????? oo = o[i];
??????????????????? if(oo instanceof Array){
??????????????????????? sA.push(i+':[');
??????????????????????? for(var b in oo){
??????????????????????????? if(oo.hasOwnProperty(b) && b!='prototype'){
??????????????????????????????? sA.push(oo[b]+',');
??????????????????????????????? if(typeof oo[b]=='object') arguments.callee(oo[b]);
??????????????????????????? }
??????????????????????? }
??????????????????????? sA.push('],');
??????????????????????? continue;
??????????????????? }else{
??????????????????????? sA.push(i+':'+oo+',');
??????????????????? }
??????????????????? if(typeof oo=='object') arguments.callee(oo);
??????????????? }
??????????? }
??????????? sA.push('},');
??????? })(this.self);
??????? return sA.slice(0).join('').replace(/\[object object\],/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
??? },
??? push:function(sName,sValue){
??????? this.self[sName] = sValue;
??????? this[sName] = sValue;
??? }
}
//用法
var jsonStr = new JsonStr(JsonObj);? //JsonObj 是一個json對象
alert(jsonStr);?
</script>
圖片:
轉載于:https://www.cnblogs.com/JerryWang1991/articles/2110110.html
總結
以上是生活随笔為你收集整理的flot中文API(转载)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微软一站式示例代码库 7月新代码示例发布
- 下一篇: Cassandra