I have the following handsontable configured:
var container = document.getElementById('example1'),
hot;
var data = [];
for (var i = 0; i < 100; i++) {
data.push({"id": 1, "rgba": "204,255,204,1"});
}
function callback (row, column, prop) {
const cellProperties = {};
cellProperties.renderer = renderer;
return cellProperties;
}
function renderer (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
var rdata = instance.getSourceDataAtRow(row);
var colour = rdata.rgba;
td.style.backgroundColor = 'rgba(' + colour + ')';
}
hot = new Handsontable(container, {
data: data
, cells: callback
// adding either of these in isolation allows the rendering to continue working. However adding both together causes only the top row to render correctly.
, hiddenColumns: true
, colWidths: 150
});
With a running example provided in the following link:
https://jsfiddle.net/JoshAdams/sgLm5ev2/
The problem I am encountering is my custom renderer is designed to set the background colours of each handsontable row based on the value in the rgba column. Which works fine initially.
However, when both the hiddenColumns: true and colWidths: 150 (or any number) properties are introduced, it causes an issue whereby only the top row of the handsontable will render correctly.
But adding either of these properties in isolation lets the rendering work correctly.
So does anyone know why this is occurring and how to fix it?
Note
While just calling hot.render() fixes the issue, its not really a solution as this causes additional unnecessary renders of handsontables which becomes a massive performance overhead in larger tables.
I can't seem to find an easy way to add legend which has switchable functionality for items in a single graph for amcharts. I searched around and found a column chart which has switchable graphs (JSFiddle 1). I found switchable items legend but it doesn't resize properly (JSFiddle 2).
This is the closest I can find to adding legends from multiple items of single graph (CodePen 1). It is from amchart website itself but there is no switchable functionality. How can I add the switchable functionality here which allows column resizing (ie. 2 items will be shown with bigger column than 10 columns)? I tried this initially to just see if switch functionality can be added but it does not work:
AmCharts.addInitHandler(function(chart) {
//check if legend is enabled and custom generateFromData property
//is set before running
if (!chart.legend || !chart.legend.enabled || !chart.legend.generateFromData) {
return;
}
var categoryField = chart.categoryField;
var colorField = chart.graphs[0].lineColorField || chart.graphs[0].fillColorsField;
var legendData = chart.dataProvider.map(function(data) {
var markerData = {
"title": data[categoryField] + ": " + data[chart.graphs[0].valueField],
"color": data[colorField]
};
if (!markerData.color) {
markerData.color = chart.graphs[0].lineColor;
}
return markerData;
});
chart.legend.data = legendData;
// here is the code I add
chart.legend.switchable=true;
}
Update - The AmCharts knowledge base demo has been updated to include the modifications below.
In order to resize the chart outright, you have to actually modify the dataProvider and remove the element from the array and redraw the chart. You can use the legend's clickMarker to store the data item into the event dataItem object and retrieve it as needed through the hidden flag. Combining the fiddles from previous solutions together, I came up with this:
/*
Plugin to generate legend markers based on category
and fillColor/lineColor field from the chart data by using
the legend's custom data array. Also allows for toggling markers
and completely removing/adding columns from the chart
The plugin assumes there is only one graph object.
*/
AmCharts.addInitHandler(function(chart) {
//method to handle removing/adding columns when the marker is toggled
function handleCustomMarkerToggle(legendEvent) {
var dataProvider = legendEvent.chart.dataProvider;
var itemIndex; //store the location of the removed item
//Set a custom flag so that the dataUpdated event doesn't fire infinitely, in case you have
//a dataUpdated event of your own
legendEvent.chart.toggleLegend = true;
// The following toggles the markers on and off.
// The only way to "hide" a column and reserved space on the axis is to remove it
// completely from the dataProvider. You'll want to use the hidden flag as a means
// to store/retrieve the object as needed and then sort it back to its original location
// on the chart using the dataIdx property in the init handler
if (undefined !== legendEvent.dataItem.hidden && legendEvent.dataItem.hidden) {
legendEvent.dataItem.hidden = false;
dataProvider.push(legendEvent.dataItem.storedObj);
legendEvent.dataItem.storedObj = undefined;
//re-sort the array by dataIdx so it comes back in the right order.
dataProvider.sort(function(lhs, rhs) {
return lhs.dataIdx - rhs.dataIdx;
});
} else {
// toggle the marker off
legendEvent.dataItem.hidden = true;
//get the index of the data item from the data provider, using the
//dataIdx property.
for (var i = 0; i < dataProvider.length; ++i) {
if (dataProvider[i].dataIdx === legendEvent.dataItem.dataIdx) {
itemIndex = i;
break;
}
}
//store the object into the dataItem
legendEvent.dataItem.storedObj = dataProvider[itemIndex];
//remove it
dataProvider.splice(itemIndex, 1);
}
legendEvent.chart.validateData(); //redraw the chart
}
//check if legend is enabled and custom generateFromData property
//is set before running
if (!chart.legend || !chart.legend.enabled || !chart.legend.generateFromData) {
return;
}
var categoryField = chart.categoryField;
var colorField = chart.graphs[0].lineColorField || chart.graphs[0].fillColorsField;
var legendData = chart.dataProvider.map(function(data, idx) {
var markerData = {
"title": data[categoryField] + ": " + data[chart.graphs[0].valueField],
"color": data[colorField],
"dataIdx": idx
};
if (!markerData.color) {
markerData.color = chart.graphs[0].lineColor;
}
data.dataIdx = idx;
return markerData;
});
chart.legend.data = legendData;
//make the markers toggleable
chart.legend.switchable = true;
chart.legend.addListener("clickMarker", handleCustomMarkerToggle);
}, ["serial"]);
Demo
I am trying to create a plugin for our chart that shows a marker on the last data in the series of a data streams. The symbol should show on the newest data only. I learnt here that i can extend the prototypes and create my chart Here like
(function (H) {
H.wrap(H.Chart.prototype, 'init', function(proceed) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
};
H.wrap(H.Chart.prototype, 'redraw', function(proceed, points) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
//Add my marker symbol here
});
}(Highcharts));
I tested the two events above, they start add the right time. However, my points is a boolean value which is not what i was expecting. I read the api docs Here yet couldn't understand how to proceed. Please if some has a better example or guidance on how to use the extension and achieve this would highly be appreciated. My data is a stream and continuos data and need to show the the marker symbol on top of the newest data only.
Update
Thanks for the response sir. We are using react-highcharts and i noticed i don't have access to the chart load event. Nonetheless, i noticed i can extend my H.Series prototype as explained Here and my event is fired on every new tick paint. I now update my code to
H.wrap(H.Series.prototype, 'drawGraph', function (proceed) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
const { chart } = this;
renderSpotIndicator(chart);
});
function renderSpotIndicator(chart){
const series = chart.series[0],
len = series.data.length - 1,
lastPoint = series.data[len];
if(lastPoint){
lastPoint.update({
marker: {
enabled: true
}
});
}
}
When i run , then i noticed my marker property does not exist in my lastPoint as hence its throwing errors. I was not able to use that. I was advised to paint the marker instead. following the example Here . I changed my code to
function renderSpotIndicator(chart){
const series = chart.series[0],
len = series.data.length - 1,
lastPoint = series.data[len];
if(lastPoint){
chart.renderer.circle(lastPoint.pointX, lastPoint.pointY, 5).attr({
fill: lastPoint.color,
padding: 10,
r: 5,
stroke: 'white',
'stroke-width': 1,
zIndex: 5
}).add();
}
}
The above is throwing errors as well. When i checked, i noticed the property circled it self is not available on my lastPoint. My lastPoint is returning correct but i am not able to set the marker on the specific point for the property was not available on the lastPoint. Please any help would be appreciated sir.
You can edit the load event and extract last point of series. Then call update to show the marker. Each time when your chart is refreshed (by add point) you need to do the same steps. Extract last point, update marker (hide), add point and show last marker.
var series = this.series[0],
len = series.data.length - 1,
lastPoint = series.data[len];
lastPoint.update({
marker: {
enabled: true
}
});
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
len = series.data.length - 1;
series.data[len].update({
marker: {
enabled: false
}
}, false);
series.addPoint([x, y], true, true);
len = series.data.length - 1;
series.data[len].update({
marker: {
enabled: true
}
}, true);
}, 1000);
Example:
- http://jsfiddle.net/ga2sym0v/
I'm working on a really small widget which displays a simple bar chart:
I'm using Chart.js for that specific task.
var canvas = this.$(".chart-canvas")[0];
if (canvas) {
var ctx = canvas.getContext("2d");
ctx.translate(0.5, 0.5);
window.barChart = new Chart(ctx).Bar(barChartData, {
responsive: true,
maintainAspectRatio: false,
showScale: false,
scaleShowGridLines: false,
scaleGridLineWidth: 0,
barValueSpacing: 1,
barDatasetSpacing: 0,
showXAxisLabel: false,
barShowStroke: false,
showTooltips: false,
animation: false
});
As you can see, I've tried
ctx.translate(0.5, 0.5);
but that didn't really help.
Is there any way to get rid of the subpixel rendering?
I've read about Bresenham's line algorithm, but don't know how to implement it there.
Any ideas/suggestions appreciated.
Thank you in advance!
Assuming you have only one color, you can do this by extending the chart and overriding the draw to do a getImageData, "rounding" (if the pixel has a R, G or B value, set it to the color) the pixel colors and a putImageData.
You could do this for multiple colors too but it becomes a tad complicated when there are two colors close by.
However the difference in bar value spacing you are seeing is because of the way Chart.js calculates the x position for the bars - there's a rounding off that happens.
You can extend the chart and override the method that calculates the x position to get rid of the rounding off
Chart.types.Bar.extend({
// Passing in a name registers this chart in the Chart namespace in the same way
name: "BarAlt",
initialize: function (data) {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
// copy paste from library code with only 1 line changed
this.scale.calculateX = function (index) {
var isRotated = (this.xLabelRotation > 0),
innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
valueWidth = innerWidth / Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
if (this.offsetGridLines) {
valueOffset += (valueWidth / 2);
}
// the library code rounds this off - we don't
return valueOffset;
}
// render again because the original initialize call does a render
// when animation is off this is the only render that happens
this.render();
}
});
You'd call it like so
var ctx = document.getElementById('canvas').getContext('2d');
var myBarChart = new Chart(ctx).BarAlt(data, {
...
Fiddle - http://jsfiddle.net/gf2c4ue4/
You can see the difference better if you zoom in.
The top one is the extended chart
I know the question was already asked before but I am very new to Dygraphs and struggling to find the answer.
I have the following datastructure in javascript:
x , Label1, Label2, label3.... label1_2, label1_3, etc...
new Date(...), 1.23,1.45,.... , .... , ....,
new Date(...), null, null, ......., 1.23,1.434
new Date(....), 1.4656, 1.6765.......,null, null,null
The whole idea is to have a plot on which a certain part of the line is dashed and the remaining part is not. I initially have 7 time series, I splitted each time serie in two (the dashed part and the non-dashed part), now I would like to highlight the whole time series ( so 2 distinct series in terms of Dygraphs the dashed serie, and the non-dashed that I splitted in two) when I pass the mouse over either the dashed region either the non dashed region.
I ve seen that people were stipulating using HihlightCallback but I am struggling to put it in practice.
What I have for the moment:
data =[new Date(), ..,..,.,,.,,.]
labels= {'A','B', ..... }
series= {'A': {strokePattern: [10, 20] }, 'B': .......}
g = new Dygraph( demo, data, {width: 1000,height: 700,labelsDivStyles: { 'textAlign': 'right' }, labels: labels,series:series, visibility: visibility, gridLineColor: 'red', gridLinePattern: [5,5], highlightCircleSize: 2,strokeWidth: 1, strokeBorderWidth: 1,highlightSeriesOpts: { strokeWidth: 3,strokeBorderWidth: 1,highlightCircleSize: 5}});
I believe my structure should be as follows:
g.updateOptions({ highlightCallback: function(event, x, points, row, seriesName) {
//1)here I need to somehow reference the other series whose label is situated N columns from the highlighted serie ( I can also reference it by its name).
// 2) Hilight the other serie
}});
I tried many different syntaxe but nothing seems to be working properly.
Could anyone please help me on this I am lost.
Here is what I would like to achieve :
http://www.google.co.uk/publicdata/explore?ds=k3s92bru78li6_#!ctype=l&strail=false&bcs=d&nselm=h&met_y=ggxwdn_ngdp&scale_y=lin&ind_y=false&rdim=world&idim=world:Earth&idim=country:AR:DZ:AU:AZ&ifdim=world&tstart=343382400000&tend=1574064000000&hl=en_US&dl=en_US&ind=false
Thanks a lot!
If I understand correctly, you've set up something like this: jsbin
Typically you style the highlighted series using highlightSeriesOpts, but that comes with the assumption that there's only a single highlighted series.
If you want to model the data this way (as separate series for actual & projected), you'll need to style the series yourself using highlightCallback. There are a few gross things about this which I'll mention below, but this is doable.
Demo: jsbin
g = new Dygraph(document.getElementById("graph"),
"X,Y,Y projected,Z,Z projected\n" +
"2006,0,,3,\n" +
"2008,2,,6,\n" +
"2010,4,,8,\n" +
"2012,6,,9,\n" +
"2014,8,8,9,9\n" +
"2016,,10,,8\n" +
"2018,,12,,6\n" +
"2020,,14,,3\n",
{
colors: ['blue', 'blue', 'red', 'red'],
series: {
'Y': { },
'Y projected': { strokePattern: [5, 5] },
'Z': { },
'Z projected': { strokePattern: [5, 5] }
},
highlightCallback: function(_, _, _, row, seriesName) {
update(seriesName, row);
},
unhighlightCallback: function() {
update();
},
highlightSeriesOpts: {},
highlightSeriesBackgroundAlpha: 1.0
});
function update(selectedSeries, row) {
var newOptions = {};
var seriesNames = g.getLabels().slice(1);
seriesNames.forEach(function(label) {
newOptions[label] = {strokeWidth: 1};
});
if (selectedSeries == 'Y' || selectedSeries == 'Y projected') {
newOptions['Y'] = newOptions['Y projected'] = {strokeWidth: 3};
} else if (selectedSeries == 'Z' || selectedSeries == 'Z projected') {
newOptions['Z'] = newOptions['Z projected'] = {strokeWidth: 3};
}
g.updateOptions({series: newOptions});
if (typeof(row) !== 'undefined') {
g.setSelection(row);
}
}
The idea is that you call updateOptions in your highlightCallback, setting the strokeWidth property for each series according to whether it (or its paired series) is selected.
There are a few gross things about this:
You have to set highlightSeriesOpts for the seriesName parameter to be passed to highlightCallback.
You need to counteract the default fading behavior of highlightSeriesOpts by setting highlightSeriesBackgroundAlpha.
Calling updateOptions clears the selection, so you have to call setSelection explicitly to re-select.
If you're willing to model the measured & projected values as a single series, then you can accomplish this more cleanly by writing a custom plotter which switches from solid to dashed lines at some point.
Here's a demo: jsbin
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"2004,0,3\n" +
"2006,2,6\n" +
"2008,4,8\n" +
"2010,6,9\n" +
"2012,8,9\n" +
"2014,10,8\n" +
"2016,12,6\n" +
"2018,14,3\n",
{
plotter: function(e) {
var ctx = e.drawingContext;
ctx.beginPath();
ctx.moveTo(e.points[0].canvasx, e.points[0].canvasy);
for (var i = 1; i < e.points.length; i++) {
var p = e.points[i];
ctx.lineTo(p.canvasx, p.canvasy);
if (p.xval == 2014) {
ctx.stroke();
ctx.beginPath();
ctx.moveTo(p.canvasx, p.canvasy);
ctx.setLineDash([5]);
}
}
ctx.stroke();
ctx.setLineDash([]);
},
highlightSeriesOpts: {
strokeWidth: 3
}
});
Because your data is a single series, you no longer need to highlight multiple series simultaneously and hence you can use highlightSeriesOpts.