Flot Data Labels - flot

I'm trying to produce a line chart using Flot, but I want the data labels to show up on the chart - meaning, I want the value of each point to appear next to that point. I feel like this should be an option, but can't find it in the API. Am I just missing something, or does someone know a workaround?
Thanks in advance.

Here is how I added the feature, including a pleasant animation effect:
var p = $.plot(...);
$.each(p.getData()[0].data, function(i, el){
var o = p.pointOffset({x: el[0], y: el[1]});
$('<div class="data-point-label">' + el[1] + '</div>').css( {
position: 'absolute',
left: o.left + 4,
top: o.top - 43,
display: 'none'
}).appendTo(p.getPlaceholder()).fadeIn('slow');
});
You can move the position and display css to a stylesheet.

The feature you want is requested here in the Flot Google group. It doesn't look like it was ever implemented (there's nothing in the API about putting any labels inside the chart itself). I think that the answer to your question is that No, it's not possible at this time to show values next to certain points on lines inside the graph.
Ole Larson, head developer on Flot, mentioned that showing labels inside the chart is different than anything else on FLot and that they would have to think about how to extend the API / plot parameters to do it.
That said, you might want to go post a question on the Flot forum or make a suggestion on the bug-tracker for the new feature. Ole Larson is actually really good at getting back to all the questions, bugs, and suggestions himself.

If anyone else is looking for a quick solution, see this plugin:
http://sites.google.com/site/petrsstuff/projects/flotvallab

Looks like the flot-valuelabels plugin is a fork of a previous flot plugin -- but the forked code renders the labels on the canvas. You can see a demo of what this looks like on the plugin's Github wiki page, here (it looks quite pleasing to the eye).

function redrawplot() {
$('.tt1').remove();
var points = plot.getData();
var graphx = $('#placeholder').offset().left;
graphx = graphx + 30; // replace with offset of canvas on graph
var graphy = $('#placeholder').offset().top;
graphy = graphy + 10; // how low you want the label to hang underneath the point
for(var k = 0; k < points.length; k++){
for(var m = 1; m < points[k].data.length-1; m++){
if(points[k].data[m][0] != null && points[k].data[m][1] != null){
if ((points[k].data[m-1][1] < points[k].data[m][1] && points[k].data[m][1] > points[k].data[m+1][1]) && (points[k].data[m-1][1] - points[k].data[m][1] < -50 || points[k].data[m][1] - points[k].data[m+1][1] > 50)) {
showTooltip1(graphx + points[k].xaxis.p2c(points[k].data[m][0]) - 15, graphy + points[k].yaxis.p2c(points[k].data[m][1]) - 35,points[k].data[m][1], points[k].color);
}
if ((points[k].data[m-1][1] > points[k].data[m][1] && points[k].data[m][1] < points[k].data[m+1][1]) && (points[k].data[m-1][1] - points[k].data[m][1] > 50 || points[k].data[m][1] - points[k].data[m+1][1] < -50)) {
showTooltip1(graphx + points[k].xaxis.p2c(points[k].data[m][0]) - 15, graphy + points[k].yaxis.p2c(points[k].data[m][1]) + 2,points[k].data[m][1], points[k].color);
}
}
}
}
}
function showTooltip1(x,y,contents, colour){
$('<div class=tt1 id="value">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y,
left: x,
'border-style': 'solid',
'border-width': '2px',
'border-color': colour,
'border-radius': '5px',
'background-color': '#ffffff',
color: '#262626',
padding: '0px',
opacity: '1'
}).appendTo("body").fadeIn(200);
}

Related

Painting individual pixels quickly in P5.js

I am trying to make an old TV static type effect in P5.js, and although I am able to make the effect work, the frame rate is quite low.
My approach is the following:
Loop through each pixel
Set the stroke to a random value
Call the point() function to paint the pixel
Initially, I was doing this in the draw function directly but it was very slow. I was getting less than 1 frame a second. So I switch to the following paint buffer approach:
const SCREEN_WIDTH = 480
const SCREEN_HEIGHT = 480
var ScreenBuffer;
function setup(){
createCanvas(SCREEN_WIDTH, SCREEN_HEIGHT);
ScreenBuffer = createGraphics(SCREEN_WIDTH,SCREEN_HEIGHT);
}
function draw(){
paintBuffer();
image(ScreenBuffer,0,0);
}
function paintBuffer(){
console.log("Painting Buffer")
for(var x = 0; x< SCREEN_WIDTH; x++){
for(var y = 0; y< SCREEN_HEIGHT; y++){
ScreenBuffer.stroke(Math.random() * 255)
ScreenBuffer.point(x,y)
}
}
}
Although I am getting a performance improvement, its nowhere near the 30 frames a second I want to be at. Is there a better way to do this?
The only way I can get reasonable performance is by filling up the screen with small squares instead with the following code:
for(var x = 0; x< SCREEN_WIDTH-10; x+=10){
for(var y = 0; y< SCREEN_HEIGHT-10; y+=10){
//ScreenBuffer.stroke(Math.random() * 255)
//ScreenBuffer.point(x,y)
ScreenBuffer.fill(Math.random() * 255);
ScreenBuffer.noStroke()
ScreenBuffer.rect(x,y,10,10)
}
}
But I would really like a pixel effect - ideally to fill the whole screen.
Believe it or not, it's actually the call to stroke() that's slowing down your sketch. You can get around this by setting the value of the pixels directly, using the set() function or accessing the pixels array directly.
More info can be found in the reference, but here's a simple example:
function setup() {
createCanvas(500, 500);
}
function draw() {
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
var c = random(255);
set(i, j, c);
}
}
updatePixels();
text(frameRate(), 20, 20);
}
Another approach you might consider is generating a few buffers that contain static images ahead of time, and then using those to draw your static. There's really no need to make the static completely dynamic, so do the work once and then just load from image files or buffers created using the createGraphics() function.

Any way to stretch/collapse canvas grid in fabric js?

I am thinking of stretching/collapsing the canvas grid using input fields. I tried the grid.js also. But this is not for fabric js, though i tried hard.
Is it possible to stretch/collapse the canvas grid by user input?
I have come up with a solution using some other guys solution those I did find in jsfiddle but I cannot find that reference link right now. I just have customized that solution to work with my code. Thanks to that guy. Here is my solution -
function draw_grid(grid_size) {
grid_size || (grid_size = 25);
currentCanvasWidth = canvas.getWidth();
currentcanvasHeight = canvas.getHeight();
// Drawing vertical lines
var x;
for (x = 0; x <= currentCanvasWidth; x += grid_size) {
this.grid_context.moveTo(x + 0.5, 0);
this.grid_context.lineTo(x + 0.5, currentCanvasHeight);
}
// Drawing horizontal lines
var y;
for (y = 0; y <= currentCanvasHeight; y += grid_size) {
this.grid_context.moveTo(0, y + 0.5);
this.grid_context.lineTo(currentCanvasWidth, y + 0.5);
}
grid_size = grid_size;
this.grid_context.strokeStyle = "black";
this.grid_context.stroke();
}
I hope this will someone someday.

How to draw SVG lines inside HighCharts barcharts?

I have a grouped bar chart just like in http://www.highcharts.com/demo/column-basic. I would like to draw horizontal lines with averages for each group (for example, historical world avg rainfall in Jan, Feb etc?) Is there a easy way to do it ? Ofcourse, each group would have different horizontal lines - but I couldn't figure out if there is a way to get handle to individual bars and do SVG lines or any other way. Much appreciate any pointers.
You can use loop to calculate average in each group and then translate position. Obviously you should need also information about tick width.
http://jsfiddle.net/rfwd9/2/
var i = 0,
avg,
yAxis = chart.yAxis[0],
r = chart.renderer,
tickWidth = chart.plotWidth / chart.series[0].data.length,
startX = chart.plotLeft,
len = chart.series[0].data.length,
seriesCount = chart.series.length;
for (i = 0; i < len; i++) {
avg = 0;
$.each(chart.series, function (j, serie) {
avg += serie.data[i].y;
});
avg = Math.floor(avg / seriesCount);
r.path(['M', startX, chart.plotHeight - yAxis.translate(avg), 'L', startX + tickWidth, chart.plotHeight - yAxis.translate(avg)])
.attr({
'stroke-width': 2,
stroke: 'red'
})
.add();
startX = startX + tickWidth;
}

How to avoid the overlapping of text elements on the TreeMap when child elements are opened in D3.js?

I created a Tree in D3.js based on Mike Bostock's Node-link Tree. The problem I have and that I also see in Mike's Tree is that the text label overlap/underlap the circle nodes when there isn't enough space rather than extend the links to leave some space.
As a new user I'm not allowed to upload images, so here is a link to Mike's Tree where you can see the labels of the preceding nodes overlapping the following nodes.
I tried various things to fix the problem by detecting the pixel length of the text with:
d3.select('.nodeText').node().getComputedTextLength();
However this only works after I rendered the page when I need the length of the longest text item before I render.
Getting the longest text item before I render with:
nodes = tree.nodes(root).reverse();
var longest = nodes.reduce(function (a, b) {
return a.label.length > b.label.length ? a : b;
});
node = vis.selectAll('g.node').data(nodes, function(d, i){
return d.id || (d.id = ++i);
});
nodes.forEach(function(d) {
d.y = (longest.label.length + 200);
});
only returns the string length, while using
d.y = (d.depth * 200);
makes every link a static length and doesn't resize as beautiful when new nodes get opened or closed.
Is there a way to avoid this overlapping? If so, what would be the best way to do this and to keep the dynamic structure of the tree?
There are 3 possible solutions that I can come up with but aren't that straightforward:
Detecting label length and using an ellipsis where it overruns child nodes. (which would make the labels less readable)
scaling the layout dynamically by detecting the label length and telling the links to adjust accordingly. (which would be best but seems really difficult
scale the svg element and use a scroll bar when the labels start to run over. (not sure this is possible as I have been working on the assumption that the SVG needs to have a set height and width).
So the following approach can give different levels of the layout different "heights". You have to take care that with a radial layout you risk not having enough spread for small circles to fan your text without overlaps, but let's ignore that for now.
The key is to realize that the tree layout simply maps things to an arbitrary space of width and height and that the diagonal projection maps width (x) to angle and height (y) to radius. Moreover the radius is a simple function of the depth of the tree.
So here is a way to reassign the depths based on the text lengths:
First of all, I use the following (jQuery) to compute maximum text sizes for:
var computeMaxTextSize = function(data, fontSize, fontName){
var maxH = 0, maxW = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none',
margin:0,
padding:0
});
$(div).css("font", fontSize + 'px '+fontName);
data.forEach(function(d) {
$(div).html(d);
maxH = Math.max(maxH, $(div).outerHeight());
maxW = Math.max(maxW, $(div).outerWidth());
});
$(div).remove();
return {maxH: maxH, maxW: maxW};
}
Now I will recursively build an array with an array of strings per level:
var allStrings = [[]];
var childStrings = function(level, n) {
var a = allStrings[level];
a.push(n.name);
if(n.children && n.children.length > 0) {
if(!allStrings[level+1]) {
allStrings[level+1] = [];
}
n.children.forEach(function(d) {
childStrings(level + 1, d);
});
}
};
childStrings(0, root);
And then compute the maximum text length per level.
var maxLevelSizes = [];
allStrings.forEach(function(d, i) {
maxLevelSizes.push(computeMaxTextSize(allStrings[i], '10', 'sans-serif'));
});
Then I compute the total text width for all the levels (adding spacing for the little circle icons and some padding to make it look nice). This will be the radius of the final layout. Note that I will use this same padding amount again later on.
var padding = 25; // Width of the blue circle plus some spacing
var totalRadius = d3.sum(maxLevelSizes, function(d) { return d.maxW + padding});
var diameter = totalRadius * 2; // was 960;
var tree = d3.layout.tree()
.size([360, totalRadius])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
Now we can call the layout as usual. There is one last piece: to figure out the radius for the different levels we will need a cumulative sum of the radii of the previous levels. Once we have that we simply assign the new radii to the computed nodes.
// Compute cummulative sums - these will be the ring radii
var newDepths = maxLevelSizes.reduce(function(prev, curr, index) {
prev.push(prev[index] + curr.maxW + padding);
return prev;
},[0]);
var nodes = tree.nodes(root);
// Assign new radius based on depth
nodes.forEach(function(d) {
d.y = newDepths[d.depth];
});
Eh voila! This is maybe not the cleanest solution, and perhaps does not address every concern, but it should get you started. Have fun!

Best way to serve / produce silhoutte of the US States?

I'm responsible for delivering pages to display primary results for the US elections State by State. Each page needs a banner with an image of the State, approx 250px by 250px. Now all I need to do is figure out how to serve / generate those images...
I've dug into the docs / examples for Protovis and think I
could probably lift the State coordinate outlines- I would have to
manually transform the coordinate data to be justified and sized
properly (ick)
At the other end of the clever/brute spectrum is an enormous sprite
or series of sprites. Even with png 8 compression the file size of
a grid of 50 non-overlapping 250x250px sprites is a concern, and
sadly such a file doesn't seem to exist so I'd have to create it
from hand. Also unpleasant.
Who's got a better idea?
Answered: the right solution is to switch to d3.
What we hacked in for now:
drawStateInBox = function(box, state, color) {
var w = $("#" + box).width(),
h = $("#" + box).height(),
off_x = 0,
off_y = 0;
borders = us_lowres[state].borders;
//Preserve aspect ratio
delta_lat = pv.max(borders[0], function(b) b.lat) - pv.min(borders[0], function(b) b.lat);
delta_lng = pv.max(borders[0], function(b) b.lng) - pv.min(borders[0], function(b) b.lng);
if (delta_lat / h > delta_lng / w) {
scaled_h = h;
scaled_w = w * delta_lat / delta_lng;
off_x = (w - scaled_w) / 2;
} else {
scaled_h = h * delta_lat / delta_lng;
scaled_w = w;
off_y = (h - scaled_h) / 2;
}
var scale = pv.Geo.scale()
.domain(us_lowres[state].borders[0])
.range({x: off_x, y: off_y},
{x: scaled_w + off_x, y: scaled_h + off_y});
var vis = new pv.Panel(state)
.canvas(box)
.width(w)
.height(h)
.data(borders)
.add(pv.Line)
.data(function(l) l)
.left(scale.x)
.top(scale.y)
.fillStyle(function(d, l, c) {
return(color);
})
.lineWidth(0)
.strokeStyle(color)
.antialias(false);
vis.render();
};
d3 seems to have the capability to do maps similar to what you want. The example shows both counties and states so you would just omit the counties and then provide the election results in the right format.
There is a set of maps on 50states.com, e.g. http://www.50states.com/maps/alabama.htm, which is about 5KB. Roughly, then, that's 250KB for the whole set. Since you mention using these separately, there's your answer.
Or are you doing more with this than just showing the outline?

Resources