gwatts / jquery.sparkline

A plugin for the jQuery javascript library to generate small sparkline charts directly in the browser
http://omnipotent.net/jquery.sparkline/
1.24k stars 278 forks source link

Show both x and y axis values on line chart #111

Open jonni83 opened 10 years ago

jonni83 commented 10 years ago

On a line graph tooltip, is there a way to show both the x and y axis values? Using the tooltipFormatFieldlist doesn't seem to have any impact.

tooltipFormatFieldlist: ['x','y']
mcmanuss8 commented 10 years ago

I had good luck using tooltipFormatter. You can get to the x and y values using fields.x and fields.y.

Try something like:

tooltipFormatter: function (sparkline, options, fields) { return "x: " + fields.x + " y: " + fields.y + "
"; }

In my case I was using unixtime for x values to represent date/time, so I had to do some custom work anyway to reformat the x value into a human readable format. There may be an easier way without setting a custom function, but I didn't look too hard...

cwgh1 commented 5 years ago

I know this is long after the discussion ended, but I found @mcmanuss8's information useful for my own sparkline where I wanted to show a time X value in the tooltip. I modified the example JS at https://stackoverflow.com/questions/31178441/jquery-getting-x-values-in-sparkline / http://jsfiddle.net/PfzXg/1231/ and produced:

// Draw a sparkline for the #sparkline element with 'minutes in the last 24 hrs' as x values function pad(n){return n<10 ? '0'+n : n} $('#sparkline').sparkline([[1200,1], [1320,4], [1360,6], [1400,3], [1440,5]], { type: 'line', height: '200', width: '240', barWidth: 20, barSpacing: 10, barColor: '#615c5a', fillColor:"white",
tooltipFormatter: function (sparkline, options, fields) { var now = new Date(Date.now()); timepoint=new Date(now-1000*60*(1440-fields.x)); timelabel=pad(timepoint.getHours()) + ":" + pad(timepoint.getMinutes()); return "" + timelabel + "hrs " + fields.y + "ug/l"; } });

I only want to show at most one day's worth of data (1440 minutes) where the x values are at least several minutes apart. So I render the data points for now x=1440, and 24 hours ago as x=0. Then I do some calculations and formatting in JS as @mcmanuss8 alluded to.