We're phasing out the Highcharts javascript visualization lib from our interactive statistics research application. It was already replaced with Rickshaw. Just now a new request came in: One certain use case has the graph display with the measurements displayed in the graph directly. This has been the case while using Highcharts (which has an option for that; called dataLabelsActivated). That should still be the case when using Rickshaw. I haven't yet found an option to make it do that. Any ideas?
How it used to display with Highcharts - highlighted in red are the measurements that should be there when using Rickshaw:
How it currently display with Rickshaw:
Apparently rickshaw doesn't support this natively. I might've done that by extending rickshar through the d3 library it is based upon (which seems to be able to do what I intended to achieve, according to the examples on its website). However, I ended up with a simple solution - added the data labels as divs manually, dependent on the distance of each datapoint from the top left corner of the graph element. Below code searches the data attribute of the graph for the data to display in labels using the color of the datapoint as it is the sole item to match a datapoint with the information in the data attribute.
$(".pointMarker").each(function( index ) {
var percentage = 0;
var currentMarkerColor = self.rgb2hex($( this ).css("border-top-color"));
self.graph.series.forEach(function(series) {
if(currentMarkerColor === series.color) {
if ( !/undef/i.test(typeof series.data[index])) {
percentage = parseFloat(series.data[index].y).toFixed(2);
}
//end loop
return false;
}
});
if (percentage > 0) {
var totalHeight = $( this ).parent().height();
var distanceTop = $( this ).css("top").replace(/[^-\d\.]/g, '') ;
//display data
$( this ).parent().append( "<div class='dataLabel' style='top:"+(parseInt($(this).css('top'), 10)-5)+"px;left:"+(parseInt($(this).css('left'), 10)-9)+"px;height:100px;width:100px;'>"+percentage+"</div>" );
}
});
and
this.rgb2hex = function (rgb){
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}
Related
I'm trying to make bar chart looks like in picture here:
Here is the result that I got
Maybe someone can suggest, how can I sticked value to xAxis?
Series I want to plot are :
series: [{
name: 'text',
data: [{"color":"#17a78b","y":3.36},
{"color":"#17a78b","y":2.1},{"color":"#17a78b","y":1.67},
{"color":"#17a78b","y":2.07},{"color":"#17a78b","y":-3.89},
{"color":"#17a78b","y":2.73},{"color":"#17a78b","y":2.34},
{"color":"#17a78b","y":2.91},{"color":"#56e8cb","y":4.94},
{"color":"#56e8cb","y":2.99},{"color":"#56e8cb","y":-2.5},
{"color":"#56e8cb","y":3.77}]
}]
Or maybe there is some way to style negative and positive value
You can make it using Highcharts.SVGElement.translate method. Each data label is SVG element which you can translate depend on your needs. This solution is more flexible because you can add more custom logic by analyzing point and label heights. Check demo and code I posted you below.
Code:
chart: {
type: 'column',
events: {
render: function() {
var chart = this,
series = chart.series[0],
offset = 3,
pointHeight,
textHeight,
translateY;
series.points.forEach(function(point) {
textHeight = point.dataLabel.getBBox().height;
pointHeight = point.shapeArgs.height;
if (pointHeight < textHeight) {
translateY = (pointHeight - textHeight / 2) + textHeight + offset;
} else {
translateY = (pointHeight - textHeight / 2) - offset;
}
translateY = (point.y < 0) ? -translateY : translateY;
point.dataLabel.translate(0, translateY);
});
}
}
}
Demo:
https://jsfiddle.net/30bxv9rc/
Api reference:
https://api.highcharts.com/class-reference/Highcharts.SVGElement#translate
https://api.highcharts.com/highcharts/chart.events.render
First set plotOptions.column.stacking to normal so that data labels are displayed inside the columns.
Next, you will need to update each point of data in the series through another function after the chart is rendered. Referring to my example, data points are looped; its value is accessed to check positive or negative; and subsequently verticalAlign and y attributes are updated so that label is displayed according to your requirement.
I have a multi-bar chart in which I've assigned a click event to the bars. This works fine until a user changes the chart type from grouped to stacked, at which point I've discovered that I need to reassign the onClick handler. This all seems to work correctly.
The problem is that after my click handler runs, whether or not the user has changed the chart type yet previously, attempting to change the chart type will result in a "groups.exit(...).watchTransition is not a function" JS error.
Chart definition:
nv.addGraph(function() {
// Defining the chart itself
var chart = nv.models.multiBarHorizontalChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.margin({top: 30, right: 20, bottom: 50, left: 275})
.showValues(true) //Show bar value next to each bar.
.tooltips(true) //Show tooltips on hover.
.valueFormat(d3.format('$,.2f'))
.groupSpacing(0.5)
.showControls(true); //Allow user to switch between "Grouped" and "Stacked" mode.
chart.yAxis
.tickFormat(d3.format('$,.2f'));
d3.select('#chart2 svg')
.datum(barData)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
},
function(){
// Set the click handler. This part works fine, but the onclick handler goes away after changing the chart type and thus needs redefined below.
// PROBLEM POINT: once this code is run, the user can no longer change the chart type. They just keep getting "groups.exit(...).watchTransition is not a function"
d3.selectAll(".nv-bar").on('click',
function(e){
var canName = e.label.split('(');
var canName = $.trim(canName[0]);
var searchTerm = canName + ' ' + e.key;
var detUrl = "/details.cfm?canName=" + encodeURIComponent(canName) + "&searchTerm=" + encodeURIComponent(searchTerm);
$("#detailsDiv").html("Loading...");
$("#detailsDiv").load(detUrl);
location.href = "#details";
});
// If I try to redefine the bar click handler in the radio button's "click" event it overwrites the built in JS used to change the chart type, so instead
// I handle it onMouseUp.
d3.selectAll(".nv-series").on('mouseup',
function(e){
setTimeout(function(){
// Just running this directly on mouseUp doesn't work. Apparently the chart needs time to load first. So we do it 100ms later, which works fine.
d3.selectAll(".nv-bar").on('click',
function(e){
var canName = e.label.split('(');
var canName = $.trim(canName[0]);
var searchTerm = canName + ' ' + e.key;
var detUrl = "/details.cfm?canName=" + encodeURIComponent(canName) + "&searchTerm=" + encodeURIComponent(searchTerm);
$("#detailsDiv").html("Loading...");
$("#detailsDiv").load(detUrl);
location.href = "#details";
});
}, 100);
});
});
watchTransition is defined by nvd3 on D3's selection prototype, if you have nv.d3.js loaded in the browser, you should be able to step with the debugger into the following code before, any chart is rendered:
d3.selection.prototype.watchTransition = function(renderWatch){
var args = [this].concat([].slice.call(arguments, 1));
return renderWatch.transition.apply(renderWatch, args);
};
I had the same issue. The reason was that I was using webpack, which bundled D3 inside my application, so the D3 that was used to draw the chart was not the D3 that NVD3 visits to add the function to the prototype. So if you are using webpack or browserify make sure to exclude D3 and add it only as reference script.
We solved this issue by downgrading to d3 3.4.4, as advised by this comment.
Here is the scenario. I've multiple highstocks say 10 charts on a single page. Currently I've written 500 lines of code to position the legend, show tooltip and refresh the legend values on mousemove.
No. of legends vary per chart. On mousemove values of all the legends are updated. I need to optimize the code I am using highstocks v1.2.2.
Above screenshot shows 2 charts. Return, Basket, vs Basket Spread are legends and it's values are updated on every mousemove.
Please find this fiddle for example. In my case legends are positioned and updated values on mouse move with hundreds of lines of code. When I move the mouse the legend values of Return and Basket of first chart and the legend values of vs Basket Spread are updated. It's working fine but with lots of javascript code. So I need to optimize it less code or with highstocks built-in feature.
Update
User #wergeld has posted new fiddle. As I've shown in screenshot when cross-hair is being moved over any chart, the legend values of all the charts should be updated.
Is there anyway to implement the same functionality with less code or is there built-in feature available in highstocks ???
Using this as a reference.
Basic example would be to use the events.mouseover methods:
plotOptions: {
series: {
point: {
events: {
mouseOver: function () {
var theLegendList = $('#legend');
var theSeriesName = this.series.name;
var theYValue = this.y;
$('li', theLegendList).each(function (l) {
if (this.innerText.split(':')[0] == theSeriesName) {
this.innerText = theSeriesName + ': ' + theYValue;
}
});
}
}
}
}
}
This is assuming I have modded the <li> to be:
$('<li>')
.css('color', serie.color)
.text(serie.name + ': NA')
.click(function () {
toggleSeries(i);
})
.appendTo($legend);
You would then need to handle the mouseout event but I do not know what you want to do there.
Working example.
EDIT:
Here is a version using your reference OHLC chart to put the values in a different legend location when any point in the chart is hovered.
plotOptions: {
series: {
point: {
events: {
mouseOver: function () {
//using the ohlc and volumn data sets created at runtime.
var stockVal = ohlc[this.index][4]; // show close value
var stockVolume = volume[this.index][1];
var theChart = $('#container').highcharts();
var theLegendList = $('#legend');
$('li', theLegendList).each(function (l) {
var legendTitle = theChart.series[l].name;
if (l === 0) {
this.innerText = legendTitle + ': ' + stockVal;
}
if (l === 1) {
this.innerText = legendTitle + ': ' + stockVolume;
}
});
}
}
}
}
}
I was having a hard time trying to figure out how to center labels on a datetime x-axis in Highcharts without using categories and tickPlacement (since tickPlacement only works on categories).
My axis was dynamically created so I could not simply set an x-offset or padding, as this would cause axes of different intervals to look strange.
After messing around with the config options I think I may have found a solution using the x-axis formatter and some css / jquery noodling in the Highcharts callback. See my answer below.
The trick is to use the x-axis labels object like this:
xAxis: {
type: 'datetime',
labels: {
useHTML: true,
align: 'center',
formatter: function () {
//using a specific class for the labels helps to ensure no other labels are moved
return '<span class="timeline_label">' + Highcharts.dateFormat(this.dateTimeLabelFormat, this.value) + '</span>';
}
}
You can see that the formatter will keep whatever dateTimeLabelFormat has been set by the user or default.
Then have a callback that does something like this:
function (chart) {
var $container = $(chart.container);
var $labels = $container.find('.highcharts-axis-labels .timeline_label');
var $thisLabel, $nextLabel, thisXPos, nextXPos, delta, newXPos;
$labels.each(function () {
$thisLabel = $(this).parent('span');
thisXPos = parseInt($thisLabel.css('left'));
$nextLabel = $thisLabel.next();
nextXPos = $nextLabel.length ? parseInt($nextLabel.css('left')) : chart.axes[0].left + chart.axes[0].width;
delta = (nextXPos - thisXPos) / 2.0;
newXPos = thisXPos + delta;
if ($nextLabel.length || $(this).width() + newXPos < nextXPos) {
$thisLabel.css('left', newXPos + 'px');
} else {
$thisLabel.remove();
}
});
});
In short, this will go through each label and determine how much it should be moved over (using css) by calculating the distance between itself and the next label. When it reaches the the last label, it either moves it over using the end of the axis for the calculation or removes it if it won't fit. This last part is just the decision I decided to make, you can probably choose to do something else like word wrap, etc.
You can see the jsfiddle here
Hope this helps some people. Also, if there are any improvements it would be great to see them here.
Based on the existing answer, there is a much simpler solution that also works when resizing the browser window (or otherwise forcing the chart to redraw), even when the tick count changes: http://jsfiddle.net/McNetic/eyyom2qg/3/
It works by attaching the same event handler to both the load and the redraw events:
$('#container').highcharts({
chart: {
events: {
load: fixLabels,
redraw: fixLabels
}
},
[...]
The handler itself looks like this:
var fixLabels = function() {
var labels = $('div.highcharts-xaxis-labels span', this.container).sort(function(a, b) {
return +parseInt($(a).css('left')) - +parseInt($(b).css('left'));
});
labels.css('margin-left',
(parseInt($(labels.get(1)).css('left')) - parseInt($(labels.get(0)).css('left'))) / 2
);
$(labels.get(this.xAxis[0].tickPositions.length - 1)).remove();
};
As you see, the extra wrapping of labels is unnecessary (at least if you do not have more than one xAxis). Basically, it works like this:
Get all existing labels (when redrawn, this includes newly added ones). 2. Sort by css property 'left' (they are not sorted this way after some redrawing)
Calculate offset between the first two labels (the offset is the same for all labels)
Set half of the offset as margin-left of all labels, effectively shifting them half the offset to the right.
Remove the rightmost label (moved outside of chart, by sometimes partly visible).
The legend to my graph only occurs whenever the plotpan event occurs. Here is my updateLegend function found below which I am sure the program goes into of course using tracing messages
However, the only time the legend updates anymore since I included the plotpan functionality, is right after a plotpan occurs. I am unsure as to what is causing this, as such I am unable to address the problem. Here is the JSFiddle that will be more helpful than the following isolated segment of code.
var updateLegendTimeout = null;
var latestPosition = null;
function updateLegend(){
var series = (plot.getData())[0];
legends.eq(0).text(series.label ="x: " + (local_x)+" y: "+ (local_y));
}
placeholder.bind("plothover", function (event, pos, item) {
if (item){
local_x = item.datapoint[0].toFixed(2);
local_y = item.datapoint[1].toFixed(2);
console.log("x:" + local_x + ", " + "y:" + local_y);
}
if (!updateLegendTimeout){
updateLegendTimeout = setTimeout(updateLegend, 50);
updateLegendTimeout = null;
}
});
What exactly is this line of code intended to do?
legends.eq(0).text(series.label ="x: " + (x)+" y: "+ (y));
It seems to be assigning the series.label but I don't believe it's actually modifying the contents of the legend div. It updates when you pan, though, because that forces a redraw of the grid (which redraws the legend).
The easiest fix is to call setupGrid manually after you change the legend.
function updateLegend(x,y){
var series = (plot.getData())[0];
var legends = $(placeholder_id+ ".legendLabel");
series.label ="x: " + (x)+" y: "+ (y);
plot.setupGrid();
clearTimeout(updateLegendTimeout);
}
This is relatively expensive, though (redrawing the grid on every mouse move). Another line of attack would be to manually set the text of the legend div but this might interfere with flots internal legend drawing. If you really want to show the nearest point position, perhaps leave the legend alone and do it in a div of your own.
Finally, I'm not quite sure where you are going with all those setTimeout. Seems like an over complication to me and you could simplify this quite a bit.
Update fiddle.