Added pixelRatio option to override canvas upscaling. Resolves #876, test included...
[dygraphs.git] / docs / tutorial.html
1 <!--#include virtual="header.html" -->
2
3 <style>
4 .annotation {
5 font-size: 12px !important;
6 }
7 </style>
8
9 <p>To use dygraphs, include the <code><a href="download.html">dygraph.js</a></code> JavaScript file
10 and <code>dygraph.css</code> CSS file. Then instantiate a <code>Dygraph</code> object.</p>
11
12 <p>Here's a basic example to get things started:</p>
13
14 <div class="example" style="clear:both;">
15 <div class="codeblock" style="float:left;width:400px;">
16 <h3 style="text-align:center">HTML</h3>
17 <pre>
18 &lt;html&gt;
19 &lt;head&gt;
20 &lt;script type=&quot;text/javascript&quot;
21 src=&quot;dygraph.js&quot;&gt;&lt;/script&gt;
22 &lt;link rel=&quot;stylesheet&quot; src=&quot;dygraph.css&quot; /&gt;
23 &lt;/head&gt;
24 &lt;body&gt;
25 &lt;div id=&quot;graphdiv&quot;&gt;&lt;/div&gt;
26 &lt;script type=&quot;text/javascript&quot;&gt;
27 g = new Dygraph(
28
29 // containing div
30 document.getElementById(&quot;graphdiv&quot;),
31
32 // CSV or path to a CSV file.
33 &quot;Date,Temperature\n&quot; +
34 &quot;2008-05-07,75\n&quot; +
35 &quot;2008-05-08,70\n&quot; +
36 &quot;2008-05-09,80\n&quot;
37
38 );
39 &lt;/script&gt;
40 &lt;/body&gt;
41 &lt;/html&gt;
42 </pre>
43 </div>
44 <div class="codeoutput" style="float:left;">
45 <h3 style="text-align:center">OUTPUT</h3>
46 <div id="graphdiv"></div>
47 <script type="text/javascript">
48 g = new Dygraph(
49
50 // containing div
51 document.getElementById("graphdiv"),
52
53 // CSV or path to a CSV file.
54 "Date,Temperature\n" +
55 "2008-05-07,75\n" +
56 "2008-05-08,70\n" +
57 "2008-05-09,80\n"
58 );
59 </script>
60 </div>
61 </div>
62
63 <p style="clear:both">In order to keep this example self-contained, the second parameter is raw CSV data. The dygraphs library parses this data (including column headers), resizes its container to a reasonable default, calculates appropriate axis ranges and tick marks and draws the graph.</p>
64
65 <p>In most applications, it makes more sense to include a CSV file instead. If the second parameter to the constructor doesn't contain a newline, it will be interpreted as the path to a CSV file. The Dygraph will perform an XMLHttpRequest to retrieve this file and display the data when it becomes available. Make sure your CSV file is readable and serving from a place that understands XMLHttpRequest's! In particular, you cannot specify a CSV file using <code>"file:///"</code>. Here's an example: (data from <a href="http://www.wunderground.com/history/airport/KNUQ/2007/1/1/CustomHistory.html?dayend=31&amp;monthend=12&amp;yearend=2007&amp;req_city=NA&amp;req_state=NA&amp;req_statename=NA">Weather Underground</a>)</p>
66
67 <div class="example" style="clear:both;">
68 <div class="codeblock" style="float:left;width:400px;">
69 <h3 style="text-align:center">HTML</h3>
70 <pre>
71 &lt;html&gt;
72 &lt;head&gt;
73 &lt;script type=&quot;text/javascript&quot;
74 src=&quot;dygraph.js&quot;&gt;&lt;/script&gt;
75 &lt;link rel=&quot;stylesheet&quot; src=&quot;dygraph.css&quot; /&gt;
76 &lt;/head&gt;
77 &lt;body&gt;
78 &lt;div id=&quot;graphdiv2&quot;
79 style=&quot;width:500px; height:300px;&quot;&gt;&lt;/div&gt;
80 &lt;script type=&quot;text/javascript&quot;&gt;
81 g2 = new Dygraph(
82 document.getElementById(&quot;graphdiv2&quot;),
83 &quot;temperatures.csv&quot;, // path to CSV file
84 {} // options
85 );
86 &lt;/script&gt;
87 &lt;/body&gt;
88 &lt;/html&gt;
89 </pre>
90 </div>
91 <div class="codeoutput" style="float:left;">
92 <h3 style="text-align:center">OUTPUT</h3>
93 <div id="graphdiv2" style="width:500px; height:300px;"></div>
94 <script type="text/javascript">
95 g2 = new Dygraph(
96 document.getElementById("graphdiv2"),
97 "temperatures.csv",
98 {}
99 );
100 </script>
101 </div>
102 </div>
103
104 <p style="clear:both;">The file used is <code><a href="temperatures.csv">temperatures.csv</a></code>.</p>
105
106 <p>There are a few things to note here:</p>
107
108 <ul>
109 <li>The Dygraph sent off an XHR to get the temperatures.csv file.</li>
110 <li>The labels were taken from the first line of <code>temperatures.csv</code>, which is <code>Date,High,Low</code>.</li>
111 <li>The Dygraph automatically chose two different, easily-distinguishable colors for the two data series.</li>
112 <li>The labels on the x-axis have switched from days to months. If you zoom in, they'll switch to weeks and then days.</li>
113 <li>Some heuristics are used to determine a good vertical range for the data. The idea is to make all the data visible and have human-friendly values on the axis (i.e. 200 instead of 193.4). Generally this works well.</li>
114 <li>The data is very spiky. A moving average would be easier to interpret.</li>
115 </ul>
116
117 <p>This problem can be fixed by specifying the appropriate options in the "additional options" parameter to the Dygraph constructor. To set the number of days for a moving average, use the <code>rollPeriod</code> option. Here's how it's done:</p>
118
119 <div class="example" style="clear:both;">
120 <div class="codeblock" style="float:left;width:400px;">
121 <h3 style="text-align:center">HTML</h3>
122 <pre>
123 &lt;html&gt;
124 &lt;head&gt;
125 &lt;script type=&quot;text/javascript&quot;
126 src=&quot;dygraph.js&quot;&gt;&lt;/script&gt;
127 &lt;link rel=&quot;stylesheet&quot; src=&quot;dygraph.css&quot; /&gt;
128 &lt;/head&gt;
129 &lt;body&gt;
130 &lt;div id=&quot;graphdiv3&quot;
131 style=&quot;width:500px; height:300px;&quot;&gt;&lt;/div&gt;
132 &lt;script type=&quot;text/javascript&quot;&gt;
133 g3 = new Dygraph(
134 document.getElementById(&quot;graphdiv3&quot;),
135 &quot;temperatures.csv&quot;,
136 {
137 rollPeriod: 7,
138 showRoller: true
139 }
140 );
141 &lt;/script&gt;
142 &lt;/body&gt;
143 &lt;/html&gt;
144 </pre>
145 </div>
146 <div class="codeoutput" style="float:left;">
147 <h3 style="text-align:center">OUTPUT</h3>
148 <div id="graphdiv3" style="width:500px; height:300px;"></div>
149 <script type="text/javascript">
150 g3 = new Dygraph(
151 document.getElementById("graphdiv3"),
152 "temperatures.csv",
153 {
154 rollPeriod: 7,
155 showRoller: true
156 }
157 );
158 </script>
159 </div>
160 </div>
161
162 <p style="clear:both;">A rolling average can be set using the text box in the lower left-hand corner of the graph (the showRoller attribute is what makes this appear). Also note that we've explicitly set the size of the chart div.</p>
163
164 <h2>Error Bars</h2>
165
166 <p>Another significant feature of the dygraphs library is the ability to display error bars around data series. One standard deviation must be specified for each data point. A <em>&plusmn;n</em> sigma band will be drawn around the data series at that point. If a moving average is being displayed, dygraphs will compute the standard deviation of the average at each point. I.E. <em>&sigma; = sqrt( (&sigma;<sub>1<sup>2</sup></sub> + &sigma;<sub>2<sup>2</sup></sub> + ... + &sigma;<sub>n<sup>2</sup></sub>) / n )</em></p>
167
168 <p>Here's a demonstration. There are two data series. One is <code>N(100,10)</code> with a standard deviation of 10 specified at each point. The other is <code>N(80,20)</code> with a standard deviation of 20 specified at each point. The CSV file was generated using Octave and can be viewed at <a href="twonormals.csv">twonormals.csv</a>.</p>
169
170 <div class="example" style="clear:both;">
171 <div class="codeblock" style="float:left;width:400px;">
172 <h3 style="text-align:center">HTML</h3>
173 <pre>
174 &lt;html&gt;
175 &lt;head&gt;
176 &lt;script type=&quot;text/javascript&quot;
177 src=&quot;dygraph.js&quot;&gt;&lt;/script&gt;
178 &lt;link rel=&quot;stylesheet&quot; src=&quot;dygraph.css&quot; /&gt;
179 &lt;/head&gt;
180 &lt;body&gt;
181 &lt;div id=&quot;graphdiv4&quot;
182 style=&quot;width:480px; height:320px;&quot;&gt;&lt;/div&gt;
183 &lt;script type=&quot;text/javascript&quot;&gt;
184 g4 = new Dygraph(
185 document.getElementById(&quot;graphdiv4&quot;),
186 &quot;twonormals.csv&quot;,
187 {
188 rollPeriod: 7,
189 showRoller: true,
190 errorBars: true,
191 valueRange: [50,125]
192 }
193 );
194 &lt;/script&gt;
195 &lt;/body&gt;
196 &lt;/html&gt;
197 </pre>
198 </div>
199 <div class="codeoutput" style="float:left;">
200 <h3 style="text-align:center">OUTPUT</h3>
201 <div id="graphdiv4" style="width:480px; height:320px;"></div>
202 <script type="text/javascript">
203 g4 = new Dygraph(
204 document.getElementById("graphdiv4"),
205 "twonormals.csv",
206 {
207 rollPeriod: 7,
208 showRoller: true,
209 errorBars: true,
210 valueRange: [50,125]
211 }
212 );
213 </script>
214 </div>
215 </div>
216
217 <p style="clear:both;">Things to note here:</p>
218
219 <ul>
220 <li>The <strong>errorBars</strong> option affects both the interpretation of the CSV file and the display of the graph. When <strong>errorBars</strong> is set to true, each line is interpreted as <em>YYYYMMDD</em>, <em>A</em>, <em>sigma_A</em>, <em>B</em>, <em>sigma_B</em>, &hellip;</li>
221 <li>The first line of the CSV file doesn't mention the error columns. In this case, it's just "Date,Series1,Series2".</li>
222 <li>The averaging visibly affects the error bars. This is most clear if you crank up the rolling period to something like 100 days. For the earliest dates, there won't be 100 data points to average so the signal will be noisier. The error bars get smaller like sqrt(N) going forward in time until there's a full 100 points to average.</li>
223 <li>The error bars are partially transparent. This can be seen when they overlap one another.</li>
224 </ul>
225
226
227 <h2 id="gviz">GViz Data</h2>
228
229 <p>The <a
230 href="http://code.google.com/apis/visualization/documentation/index.html">Google
231 Visualization API</a> provides a standard interface for describing data.
232 Once you've specified your data using this API, you can plug in any
233 GViz-compatible visualization. dygraphs is such a visualization. In
234 particular, it can be used as a drop-in replacement for the
235 AnnotatedTimeline visualization used on Google Finance and other sites. To
236 see how this works, check out the <a href="tests/annotation-gviz.html">gviz
237 annotation demo.</a></p>
238
239 <p>Here is another demonstration of
240 <a href="http://danvk.org/dygraphs/tests/gviz.html">how to use dygraphs a GViz visualization</a>.
241 </p>
242
243 <h2 id="baseball">Charting Fractions</h2>
244
245 <p>Situations often arise where you want to plot fractions, e.g. the fraction of respondents in a poll who said they'd vote for candidate X or the number of hits divided by at bats (baseball's batting average). Fractions require special treatment for two main reasons:</p>
246
247 <ul>
248 <li>The average of <code>a1/b1</code> and <code>a2/b2</code> is <code>(a1+a2)/(b1+b2)</code>, not <code>(a1/b1 + a2/b2)/2</code>.</li>
249 <li>The normal approximation is not always applicable and more sophisticated confidence intervals (e.g. the <a href="http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval">Wilson confidence interval</a>) must be employed to avoid ratios that exceed 100% or go below 0%.</li>
250 </ul>
251
252 <p>Fortunately, dygraphs handles both of these for you! Here's a chart and the command that generated it:</p>
253
254 <div style="width:750px; text-align:center; font-weight: bold; font-size: 125%;">Batting Average for Ichiro Suzuki vs. Mariners (2004)</div>
255 <div id="baseballdiv" style="width:750px; height:300px;"></div>
256 <script type="text/javascript">
257 new Dygraph(
258 document.getElementById("baseballdiv"),
259 "suzuki-mariners.txt",
260 {
261 fractions: true,
262 errorBars: true,
263 showRoller: true,
264 rollPeriod: 15
265 }
266 );
267 </script>
268
269 <b>Code:</b>
270 <pre>
271 new Dygraph(
272 document.getElementById(&quot;baseballdiv&quot;),
273 &quot;suzuki-mariners.txt&quot;,
274 {
275 fractions: true,
276 errorBars: true,
277 showRoller: true,
278 rollPeriod: 15
279 }
280 );
281 </pre>
282
283 <p>The <code>fractions</code> option indicates that the values in each column should be parsed as fractions (e.g. "1/2" instead of "0.5"). The <code>errorBars</code> option indicates that we'd like to see a confidence interval around each data point. By default, when <code>fractions</code> is set, you get a Wilson confidence interval. If you look carefully at the chart, you can see that the error bars are asymmetric.</p>
284
285 <p>A couple things to notice about this chart:</p>
286
287 <ul>
288 <li>The error bars for Ichiro's batting average are larger than for the Mariners', since he has far fewer at bats than his team.</li>
289 <li>dygraphs makes it easy to see "batting average over the last 30 games". This is ordinarily quite difficult to compute. It makes it clear where the "hot" and "cold" part of Suzuki's season were.</li>
290 <li>If you set the averaging period to something large, like 200, you'll see the team's and player's batting average through that game. The final number is the overall batting average for the season.</li>
291 <li>Where the error bars do not overlap, we can say with 95% confidence that the series differ. There is a better than 95% chance that Ichiro was a better hitter than his team as a whole in 2004, the year he won the batting title.</li>
292 </ul>
293
294 <h2 id="stock">One last demo</h2>
295
296 <p>This chart shows monthly closes of the Dow Jones Industrial Average, both in nominal and real (i.e. adjusted for inflation) dollars. The shaded areas show its monthly high and low. CPI values with a base from 1982-84 are used to adjust for inflation.</p>
297
298 <div id="dow_chart" style="width:750px; height:350px;"></div>
299 <p><b>Display: </b>
300 <input type=checkbox id=0 onClick="stockchange(this)" checked>
301 <label for="0"> Nominal</label>
302 <input type=checkbox id=1 onClick="stockchange(this)" checked>
303 <label for="1"> Real</label>
304 <input type=checkbox id=ann onClick="annotationschange(this)" checked>
305 <label for="ann"> Annotations</label>
306 </p>
307
308 <script type="text/javascript">
309 var stock_annotations = [
310 {
311 series: "Real",
312 x: "1929-08-15",
313 shortText: "A",
314 text: "1929 Stock Market Peak",
315 cssClass: 'annotation'
316 },
317 {
318 series: "Nominal",
319 x: "1987-08-15",
320 shortText: "B",
321 text: "1987 Crash",
322 cssClass: 'annotation'
323 },
324 {
325 series: "Nominal",
326 x: "1999-12-15",
327 shortText: "C",
328 text: "1999 (.com) Peak",
329 cssClass: 'annotation'
330 },
331 {
332 series: "Nominal",
333 x: "2007-10-15",
334 shortText: "D",
335 text: "All-Time Market Peak",
336 cssClass: 'annotation'
337 }
338 ];
339
340 // From http://www.econstats.com/eqty/eq_d_mi_3.csv
341 stockchart = new Dygraph(
342 document.getElementById('dow_chart'),
343 "dow.txt",
344 {
345 showRoller: true,
346 customBars: true,
347 labelsKMB: true,
348 drawCallback: function(g, is_initial) {
349 if (!is_initial) return;
350 g.setAnnotations( stock_annotations );
351 }
352 }
353 );
354
355 function stockchange(el) {
356 stockchart.setVisibility(el.id, el.checked);
357 }
358
359 function annotationschange(el) {
360 if (el.checked) {
361 stockchart.setAnnotations(stock_annotations);
362 } else {
363 stockchart.setAnnotations([]);
364 }
365 }
366 </script>
367 <!--
368
369 Here is a script to regenerate the Dow Jones plot:
370
371 # Get unadjusted DJIA data in a nice format:
372 curl -O http://www.econstats.com/eqty/eq_d_mi_3.csv
373 sed '1,17d' eq_d_mi_3.csv | cut -d, -f1,6 | perl -pe 's/(\d{4}-\d\d)-\d\d/$1/g' | perl -pe 's/, */\t/' | grep -v 'na' | perl -ne 'chomp; ($m,$v) = split/\t/; $close{$m} = $v; if ($low{$m} == 0 || $v < $low{$m}) { $low{$m}=$v } if ($v > $high{$m}) { $high{$m} = $v } END { for $x(sort keys %close) { print "$x\t$low{$x}\t$close{$x}\t$high{$x}\n" } } ' > monthly-djia.tsv
374
375 # Fetch and format the CPI data:
376 curl 'http://data.bls.gov/PDQ/servlet/SurveyOutputServlet?series_id=CUUR0000SA0&years_option=all_years&periods_option=all_periods&output_type=column&output_format=text&delimiter=comma' > cpi-u.txt
377 sed '1,/Series Id,Year,/d' cpi-u.txt | sed '/^$/,$d' | cut -d, -f2,3,4 | perl -ne 'print if /,M(0[0-9]|1[012]),/' | perl -pe 's/(\d{4}),M(\d{2}),/$1-$2\t/g' > cpi-u.tsv
378
379 # Merge:
380 join -t' ' cpi-u.tsv monthly-djia.tsv > annotated-djia.tsv
381 perl -ne 'BEGIN{print "Month,Nominal,Real\n"} chomp; ($m,$cpi,$low,$close,$high) = split /\t/; $cpi /= 100.0; print "$m-15,$low;$close;$high,",($low/$cpi),";",($close/$cpi),";",($high/$cpi),"\n"' annotated-djia.tsv > dow.txt
382
383 -->
384
385 <h2>Common Gotchas</h2>
386
387 <p>Here are a few problems that I've frequently run into while using the dygraphs library.</p>
388
389 <ul>
390 <li>If your chart doesn't display, be sure to check your browser's JavaScript error console. dygraphs makes every attempt to log errors and warnings, and these can often guide you in the right direction.</li>
391 <li>Make sure your CSV files are readable! If your graph isn't showing up, the XMLHttpRequest for the CSV file may be failing. You can determine whether this is the case using tools like <a href="http://www.getfirebug.com/">Firebug</a>.</li>
392 <li>Make sure your CSV files are in the correct format. They must be of the form <code>YYYYMMDD, series1, series2, </code>&hellip; . And if you set the <code>errorBars</code> property, make sure you alternate data series and standard deviations.</li>
393 <li>dygraphs are not happy when placed inside a <code>&lt;center&gt;</code> tag. This applies to the CSS <code>text-align</code> property as well. If you want to center a Dygraph, put it inside a table with <code>align = center</code> set.</li>
394 <li>Don't set the <code>dateWindow</code> property to a date. It expects milliseconds since epoch, which can be obtained from a JavaScript Date object's valueOf method.</li>
395 <li>Make sure you don't have any trailing commas in your call to the Dygraph constructor or in the options parameter. Firefox, Chrome and Safari ignore these but they can cause a graph to not display in Internet Explorer.</li>
396 </ul>
397
398 <h2>What next?</h2>
399
400 <p>If you need to support Internet Explorer, check out our <a href="ie.html">notes on IE</a>.</p>
401
402 <p>To get some inspiration, look at how the <a href="gallery/">charts in our gallery</a> are built.</p>
403
404
405 <!--#include virtual="footer.html" -->