C3.js combination chart with time series - tooltip not functional - c3.js

I've been trying for 3 days to get this chart to display the way I want it to. Everything was working 100% until I realized the grouped bar chart numbers were off.
Example: When the bottom bar value equals 10 and the top bar value equals 20, the top of the grouped bar read 30. This is the default behavior, but not how I want to represent my data. I want the top of the grouped bar to read whatever the highest number is, which lead me to this fiddle representing the data exactly how I wanted to.
After refactoring my logic, this is what I have so far. As you can see the timeseries line is broken up and the tooltip is not rendering the group of data being hovered over.
My questions:
1) How to get the tooltip to render all three data points (qty, price, searches)
2) How to solidify the timeseries line so it's not disconnected
Any help would be greatly appreciated so I can move on from this 3 day headache!
Below is most of my code - excluding the JSON array for brevity, which is obtainable at my jsfiddle link above. Thank you in advance for your time.
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x-axis',
type: 'bar',
json: json,
xFormat: '%Y-%m-%d',
keys: {
x: 'x-axis',
y: 'searches',
value: ['qty', 'searches', 'price']
},
types: {
searches: 'line'
},
groups: [
['qty', 'price']
],
axes: {
qty: 'y',
searches: 'y2'
},
names: {
qty: 'Quantity',
searches: 'Searches',
price: 'Price ($)'
},
colors: {
price: 'rgb(153, 153, 153)',
qty: 'rgb(217, 217, 217)',
searches: 'rgb(255, 127, 14)'
}
},
bar: {
width: {
ratio: 0.60
}
},
axis: {
x: {
type: 'timeseries',
label: { text: 'Timeline', position: 'outer-right' },
tick: {
format: '%Y-%m-%d'
}
},
y: {
type: 'bar',
label: {
text: 'Quantity / Price',
position: 'outer-middle'
}
},
y2: {
show: true,
label: {
text: 'Searches',
position: 'outer-middle'
}
}
},
tooltip: {
grouped: true,
contents: function(d, defaultTitleFormat, defaultValueFormat, color) {
var data = this.api.data.shown().map(function(series) {
var matchArr = series.values.filter(function(datum) {
return datum.value != undefined && datum.x === d[0].x;
});
if (matchArr.length > 0) {
matchArr[0].name = series.id;
return matchArr[0];
}
});
return this.getTooltipContent(data, defaultTitleFormat, defaultValueFormat, color);
}
}
});

1) If I got it right, you want tooltip to show all values, even if some of them are null.
Null values are hidden by default. You can replace them with zero (if it is suitable for your task) and thus make them visible.
Also, it seems to me that there is a shorter way to get grouped values:
var data = chart.internal.api.data().map(function(item) {
var row = item.values[d[0].index]; // get data for selected index
if (row.value === null) row.value = 0; // make null visible
return row;
});
2) I think you are talking about line.connectNull option:
line: {
connectNull: true
}
UPDATE
Looks like having duplicate keys breaks work of api.data() method.
You need to change json structure to make keys unique:
Before:
var json = [
{"x-axis":"2017-07-17","qty":100},
{"x-axis":"2017-07-17","price":111},
{"x-axis":"2017-07-17","searches":1},
{"x-axis":"2017-07-18","qty":200},
{"x-axis":"2017-07-18","price":222},
{"x-axis":"2017-07-18","searches":2}
];
After:
var json = [
{"x-axis":"2017-07-17","qty":100,"price":111,"searches":1},
{"x-axis":"2017-07-18","qty":200,"price":222,"searches":2}
];
See fiddle.

Related

Can we add event listeners to "Vega-Lite" specification?

I am new to Vega and Vega-Lite. I am creating a simple bar chart using Vega-Lite but I am not able to add any event listeners e.g. "hover".
I want to hover a bar and change the color of the bar.
If you're using Vega-Embed, it returns a promise with a reference to the view which allows you to use addEventListener - explained in the docs here.
Here is an example:
const width = 600
const color = blue
embed(element, {
$schema: 'https://vega.github.io/schema/vega-lite/3.0.0-rc6.json',
data: { 'values': data },
mark: {
type: 'line',
color,
point: {
color,
}
},
width,
height: width / 2,
encoding: {
'x': {
field: 'label',
type: 'temporal',
},
'y': {
field: 'value',
type: 'quantitative',
},
}
}).then(({spec, view}) => {
view.addEventListener('mouseover', function (event, item) {
console.log(item.datum)
})
})

ZoomRange Highstock works not correct?

I made a Highstock diagramm and got aproblem with zooming on the yAxis.
I have a Button and 2 textfield to get the wanted min/max values for the axis. With min:0, max: 100 it works well. With min:0, max:80 it doesn't (max will still be 100 in the Diagramm).
If I use the mouse for zooming it works well (even a min of: 3.7 and a max of 3.894 is possible). But using the mouse is not an Option, because in the later Diagramm there will be 3 yAxes with individual zoom.
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'];
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
function createChart() {
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
chart:{
zoomType: 'xy'
},
yAxis: [
{
labels: {
format: '{value}',
},
height: '100%',
opposite: false,
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
],
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
},
function(chart){
$('#btn').click(function(){
var min = temp_min.value,
max = temp_max.value;
chart.yAxis[0].setExtremes((min),(max));
});
});
}
$.each(names, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
if(seriesCounter==0){
seriesOptions[i] = {
name: name,
data: data,
yAxis: 0
};
} else {
seriesOptions[i] = {
name: name,
data: data,
yAxis: 0
};
}
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
});
JSFiddle
Another Question: Is it possible to set up a scrollbar for the yAxis as well?
Thanks for your help, Patrick
This is related with fact that tickInterval is not regular, so is rounded to value (like 100). The solution is using tickPositioner which calculates ticks, based on extremes which you define.
tickPositioner: function (min,max) {
var positions = [],
tick = Math.floor(min),
increment = Math.ceil((max - min) / 5);
for (tick; tick - increment <= max; tick += increment) {
positions.push(tick);
}
return positions;
},
http://jsfiddle.net/6s11kcwd/
The scrollbar is supported only for xAxis.

Handsontable change a column source

Is it possible to change the source in a Handsontable instance when inside an event?
Below is my code:
var container2 = $('#example2');
var hot2 = new Handsontable(container2, {
data: {},
minRows: 5,
colHeaders: ['Car', 'Year', 'Car Color'],
columns: [
{
type: 'autocomplete',
source: ['BMW', 'Chrysler', 'Nissan', 'Suzuki', 'Toyota', 'Volvo'],
strict: true,
allowInvalid: false
}, ,
{},
{
type: 'autocomplete',
source: ['yellow', 'red', 'orange', 'green', 'blue', 'gray', 'black', 'white', 'purple', 'lime', 'olive', 'cyan'],
strict: true,
allowInvalid: false
}]
});
Handsontable.hooks.add('afterChange', afterChangedCallback, hot2);
function afterChangedCallback(p) {
console.log(p);
if (p[0][1] == 0) {
alert('This means the first column has changed, I now want to update the colors here');
}
}
When a user selects a different car brand, I only want to populate the dropdown of "Car Color" with certain colors. Thus, not all car brands has the same colors.
EDIT
I updated the callback function to this based on the accepted answer:
function afterChanged(p) {
console.log(p);
if (p[0][1] == 0) {
hot2.updateSettings({
cells: function (row, col, prop) {
if (row == p[0][0] && col == 2) {
var cellProperties = {};
cellProperties.source = ['red', 'yellow', 'blue'];
return cellProperties;
}
}
});
}
}
Yup, you can use the updateSettings method to change the source of an entire column or particular cell. You probably want per-cell so I would do:
hot.updateSettings({
cells: newCellDefinitionFunction()
})
Of course this new definition is up to you to figure out. It could just be returning the same cellProperties each time but check on some global array for what sources to use for which cells.

Render bands / bandData in jqplot when series contains null values

I am using jqplot to render a line graph.
My series data looks like:
results =[
['1/1/2014', 1000],
['2/1/2014', 2000],
['3/1/2014', 3000],
['4/1/2014', 4000],
['5/1/2014', null]
];
my call to jqplot looks something like
$.jqplot('myChart', results,
{
series: [
{
rendererOptions: {
bands: {
show: true,
interval: '10%'
},
}
}
]
});
The chart will render, but it will be missing the 10% bands above and below.
If i change the null value
['5/1/2014', null]
to be
['5/1/2014', 5000]
then the bands will render correctly.
My does data have some missing values. Is there any way to make the bands render for non-null data points on the line, even if the line does have some null data points?
Instead of sending null for those values, omit them entirely and depend on the dateAxisRenderer to correctly space the values on the axis.
results = [
['1/1/2014', 1000],
['2/1/2014', 2000],
['3/1/2014', 3000],
['4/1/2014', 4000],
['6/1/2014', 3500]
];
$.jqplot ('myChart', [results],
{
series: [{
rendererOptions: {
bands: {
show: true,
interval: '10%'
}
}
}],
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer
}
}
});
JSFiddle version here (don't forget the extra script reference for dateAxisRenderer)
http://jsfiddle.net/4vmNf/1/
Alternatively, you can pass separate arrays for upper & lower band data, and this does not have to follow the same intervals as the underlying data array.
lowerBand = [];
upperBand = [];
for(var i = 0; i < results.length; i++) {
if (results[i][1]) {
lowerBand.push([results[i][0], results[i][1] * 0.9]);
upperBand.push([results[i][0], results[i][1] * 1.1]);
} else {
// not clear to me how you want to calculate band for missing values
lowerBand.push([results[i][0], 3500]);
upperBand.push([results[i][0], 6500]);
}
}
And then use bandData option:
series: [{
rendererOptions: {
bandData: [lowerBand, upperBand]
}
}]

How to get a simple line for average on a bar chart in jqPlot

I am working with a bar chart in jqPlot where I need to show the average with a separate line on the chart. My question is how to do that? Would I need to use a Line chart for this? I have looked at few Line chart examples but they are shown as a trend in the bar chart which starts from the very first bar on the chart rather than showing the average.What I need is plotting a line using the average of all those bars displayed on the chart (screen shots as below)
My JSON string to plot the data is as follows:
var commonOption= {
title: ''
,stackSeries: true
,captureRightClick: true
,seriesDefaults:{
renderer:$.jqplot.BarRenderer
,rendererOptions: {
barMargin: 15
,highlightMouseDown: true
,fillToZero: true
},
pointLabels: {
show: true
,formatString: '%.1f'
,seriesLabelIndex:1
,hideZeros:false
}
}
,seriesColors: ['#A9CB5E']
,axes: {
xaxis: {
tickOptions:{angle:-45}
,tickRenderer: $.jqplot.CanvasAxisTickRenderer
,renderer: $.jqplot.CategoryAxisRenderer
,ticks: []
},
yaxis: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
,padMin: 0
,pad: 1.1
, label: 'Percentage (%)'
,rendererOptions: { forceTickAt0: true}
//,min: 0
//,tickOptions:{formatString: '%.0f'},
}
}
,negativeSeriesColors:['#F08080']
/*,legend: {
show: true
,location: 'e'
,placement: 'outsideGrid'
}*/
,highlighter:{
show: true
,tooltipLocation: 's'
,yvalues: 2
,bringSeriesToFront:true
,showMarker:false
,tooltipAxes: 'y'
,formatString: "%n%s"
}
,cursor:{
show: true
,zoom:true
,showTooltip:false
,constrainZoomTo: 'y'
}
,grid:{
background: '#f8f8f8'
}
};
I believe what you are looking for is the jqplot CanvasOverlay functionality http://www.jqplot.com/deploy/dist/examples/canvas-overlay.html
After declaring all of you options and data in the function (in your example after "grid" option):
grid:{
background: '#f8f8f8'
},
canvasOverlay: {
show: true,
objects: [
{horizontalLine: {
name: 'avergae',
y: 20.8, //**AVERAGE_FLOAT_VALUE**
lineWidth: 2,
color: 'black',
shadow: false
}}
]
}
EDIT:
Yes, sorry about that. be sure not to forget to include "jqplot.canvasOverlay.min.js "
Hi I think it is better to implement a function that automatically calculates the average of the data points into the array. In fact the average of your bar char is about 18 and not 20!!
I suggest to implement a function for doing thi. See this jsFiddle example.
There is an article where it is shown how to draw and calculate the statistics for a bar chart: average, median, mode and standard deviation at this link:
http://www.meccanismocomplesso.org/en/mean-mode-median-barchart/ .
Array.prototype.average=function(){
var sum=0;
var j=0;
for(var i=0;i<this.length;i++){
if(isFinite(this[i])){
sum=sum+parseFloat(this[i]);
j++;
}
}
if(j===0){
return 0;
}else{
return sum/j;
}
}
...
canvasOverlay: {
show: true,
objects: [
{dashedHorizontalLine: {
name: 'average',
y: data.average(),
lineWidth: 3,
color: 'black',
shadow: false
}}
]
}

Resources