Chart js: generate dynamic labels according to the data - charts

I'm fetching the chart dynamically ..
This is chart of current month which ranges from 1-31
I want to have a range filter for example:
2012/01/1 to 2014/01/1
How can I do this labels will be too many?
Lets say I decide on doing it yearly but what if the user want to see from this year jan to nov i should make it monthly then how I can know? if its monthly or yearly or what is the best way to do this?

I think it would be the best to add two tabs with names monthly and yearly, so user can easy click on tab to change views. For example on monthly view, it will be too much to show all months in one chart(I think it will be mess with data), you should do this only with one month. Just add datetimepicker only with months(same for years), on change you can call function which will change chart also(see here how it works https://www.tutorialspoint.com/How-does-jQuery-Datepicker-onchange-event-work). Also you can set the range of years.
So, now when you have function which will change chart, just change data by getting selected month and your data for this month. There is an update function, which you can call when you have updated data and it will change chart(See docs: https://www.chartjs.org/docs/latest/developers/updates.html).
Here is an example of code for adding new dataset to existing chart by clicking button:
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[barChartData.datasets.length % colorNames.length];
var dsColor = window.chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (barChartData.datasets.length + 1),
backgroundColor: color(dsColor).alpha(0.5).rgbString(),
borderColor: dsColor,
borderWidth: 1,
data: []
};
for (var index = 0; index < barChartData.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
barChartData.datasets.push(newDataset);
window.myBar.update();
});

Just in case anybody was searching and found this thread because they wanted dynamic units for their plotted points in Chart.js, then the below code will give you and idea of how to configure your options -> tooltips -> callbacks -> label
options: {
tooltips: {
callbacks: {
label: (item) => {
if (condition1 == true) {
return (item.yLabel / 1000000000).toFixed(2) + ' Gbps'
}
else if (condition2 == true) {
return (item.yLabel / 1000000).toFixed(2) + ' Mbps'
}
else if (condition3 == true) {
return (item.yLabel / 1000).toFixed(2) + ' Kbps'
}
else {
return item.yLabel.toFixed(2) + ' bps'
}
},
},
},
},
This is an example that converts bps to Kbps, Mbps, Gbps, etc. as necessary.

Related

How can I enter 5M or 10k into AG Grid so it shows the full number (i.e. 5,000,000 or 10,000)

Our users need quick and reliable data entry so they want to type 'M' into a number cell in AG Grid but have that converted into a number. e.g. 5M will become 5000. I dont want to change the cell type to text or do a value formatter if at all possible as that then brings its own problems.
You can use a Value Setter to set the value to be entered into the cell after editing a cell
{
headerName: 'B',
field: 'b',
valueSetter: function (params) {
const THOUSAND = 'k';
const MILLION = 'm';
const lastCharacter = params.newValue
.charAt(params.newValue.length - 1)
.toLowerCase();
if (lastCharacter == THOUSAND) {
var newValInt = parseInt(params.newValue) * 1000;
} else if (lastCharacter == MILLION) {
var newValInt = parseInt(params.newValue) * 1000000;
} else {
var newValInt = parseInt(params.newValue);
}
var valueChanged = params.data.b !== newValInt;
if (valueChanged) {
params.data.b = newValInt;
}
return valueChanged;
},
},
See this implemented in the following plunkr
If you are using AdapTable with AG Grid then you can use the Shortcut Module.
This allows you to define shortcuts at design time or run time.
So in this case you would define a shortcut ('M' for Multiply by 1000) and then each time the user types 5M, AdapTable will convert it to 5,000 but the column will remain a numeric one.
Shortcut: {
Shortcuts: [
{
Scope: { DataTypes: ['Number'] },
ShortcutKey: 'M',
ShortcutOperation: 'Multiply',
ShortcutValue: 1000,
},
],
},

Highcharts tooltip refresh not working correctly

I am trying to show the tooltip across multiple charts when the user hovers over any one of the charts.
series: {
point: {
events: {
mouseOver: function() {
syncTooltip(this.series.chart.container, this.x);
}
}
}
}
function syncTooltip(container, p) {
_.each(totalCharts, (chartType) => {
let chartContainer = $('#'+chartType);
let chart = chartContainer.highcharts();
if (chart && chart.tooltip && container.id != chart.container.id) {
//I am fetching all points in chart.series whose 'x' value matches with the function parameter 'p'
var points = process(chart.series);
if(points.length > 0) {
chart.tooltip.refresh(points);
}
}
});
}
The points array is getting populated correctly. However the charts tooltips are not showing up correctly. Even the highlighted points in the charts are showing up wrong.
In the above image, I added labels for each data point (x and y coordinates separated by a space).
In the second chart, point three is highlighted whereas point two should be the one highlighted to be in sync with first chart

Chartjs: Is it possible to add phases in line chart?

Hello I want to create a dynamic chart that looks like this: phases in line chart
Is it possible with ChartJs to create vertical lines at certain milestones? (If possible also give each phase another color)
If not, what other libraries can handle dynamic line chart libraries that support phases?
Using Chart.js plugins can help you with this. They let you handle specific events that are triggered during the chart creation like beforeInit, afterUpdate or afterDraw and are also easy to implement :
var myPlugin = {
afterDraw: function(chart) {
// This will be triggered after the chart is drawn
}
};
Chart.pluginService.register(myPlugin);
A plugin doing what you are looking for will be linked below, but first let me explain how it works.
In your chart options, you'll need to add a new property, called phases, which is an array :
// The following is an example that won't work with every chart
options: {
scales: {
xAxes: [{
// `from` & `to` must exist in your xAxe ticks
phases: [{
from: "January",
to: "March",
// You can also define the color here
color: "blue"
},
{
from: "May",
to: "June",
color: "red"
}]
}]
}
}
And then, here is the plugin that use this information :
var phasePlugin = {
// You need to handle the `afterDraw` event since you draw phases edges
// after everything is drawn
afterDraw: function(chart)
{
// All the variables the plugin needs follow ...
var ctx = chart.chart.ctx;
var xAxeId = chart.config.options.scales.xAxes[0].id;
var xAxe = chart.scales[xAxeId];
var yAxeId = chart.config.options.scales.yAxes[0].id;
var yAxe = chart.scales[yAxeId];
var ticks = xAxe.ticks;
var phases = chart.config.options.scales.xAxes[0].phases;
// For every phase ...
for (var i = 0; i < phases.length; i++) {
// We check if the tick actually exists
if (ticks.indexOf(phases[i].from) == -1 || (ticks.indexOf(phases[i].to) == -1)) {
// Else, we skip to the next phase
continue;
}
// We get the x position of the first limit tick
var xPos = ((xAxe.width - xAxe.paddingRight) / xAxe.maxIndex) * ticks.indexOf(phases[i].from) + xAxe.left + 1;
// And draw the dashed line
ctx.setLineDash([8, 8]);
ctx.strokeStyle = phases[i].color;
ctx.strokeRect(xPos, yAxe.top, 0, yAxe.height);
// Same for the other limit
xPos = ((xAxe.width - xAxe.paddingRight) / xAxe.maxIndex) * ticks.indexOf(phases[i].to) + xAxe.left + 1;
ctx.strokeStyle = phases[i].color;
ctx.strokeRect(xPos, yAxe.top, 0, yAxe.height);
ctx.setLineDash([1,0]);
}
}
};
You can see a fully working example in this jsFiddle and here is its result :

Variable Colors in Google Bar Charts

I have a survey web app that serves a number different kinds of questions to Google Chart. In fact there are 26 of them. I need to change the colors of the bars depending on the question case. I CAN accomplish this, by copying the var options inside of each if (questioncase = 'X') 26 times - but I'm hoping for a short cut. Any thoughts would, as always be, much appreciated.
var options = {
//width:w,
width:500,
height:h,
isStacked:true,
chartArea:{height:chartHeight,left:l,width:cw},
backgroundColor:'transparent',
bar:{groupWidth:'80%'},
tooltip: {isHtml:true},
legend:{position:pos,maxLines:50},
hAxis: {title: 'Percentage',minValue:0,maxValue:100},
hAxis: { textPosition: 'none',ticks: [0]},
colors: ['#eeeeee', '#eeeeee', '#e4d00a', '#b30000', '#990000']
}
if (questioncase == 'A') {
var options = {
colors: ['#134e13', '#008900', '#e4d00a', '#b30000', '#990000']
}
}
You can reuse the same options object, just change the colors property.
if (questioncase == 'A') {
options.colors = ['#134e13', '#008900', '#e4d00a', '#b30000', '#990000'];
}

jQuery Datepicker popup tooltip

I'm really just looking to assign additional information to dates. I am currently setting up datepicker with the following:
beforeShowDay: function(date){
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if ($.inArray(dmy, ajaxDates) != -1) {
return [true, "","Available"];
} else {
return [false,"","unAvailable"];
}
},
Where ajaxDates is an array containing a list of available dates such as:
var ajaxDates = [ "26-2-2015", "27-2-2015"];
It's for a booking system were I have another array containing the number of seats available for every date. I had seen a post that I can no longer find were someone was attaching additional information to the dates. If someone could point me in the right direction that would be great!
Edit: I have noticed that the a title is attached to each date which on hover shows the tooltip as "Available" or "Unavailable". Is there any easy method to access through the datepicker?
The solution that I was referring to was:
Add custom parameter to jQuery UI Datepicker
An example of how to set additional parameters is as followed:
var input = $("#datepicker");
var result = $("#result");
var courses = {
"02-09-2013" : "history",
"10-09-2013": "physics"
};
input.datepicker({
dateFormat: 'dd-mm-yy',
showWeek: true,
firstDay: 1,
numberOfMonths: 3,
onSelect: function(dateText, pickerObj){
result.attr("data-course-id", courses[dateText]);
course.innerHTML = courses[dateText];
},
altField: "#result"
});
http://jsfiddle.net/Seandeburca/qbLwD/