How to make xaxis to show dates using jqPlots - date

I'm trying to make a bar chart using jqPlots. I'm taking data from database with ajax. In vertical it is shown prices-they are correct. But my problem is how to show dates in xaxis. Every bar should be placed in the correct place in horizontal depending on date.For example my current dates for the three bars are: 2015-06-06,2015-06-08, 2015-06-30.
If I use renderer: $.jqplot.CategoryAxisRenderer, dates in xaxis are shown correct but bars aren't positioned dependent on that date.
http://prntscr.com/7ew365
If I use renderer:$.jqplot.DateAxisRenderer, it looks in that way:
http://prntscr.com/7ew1ot
Dates aren't displayed. They should be:
var ticks2 = ['2015-05-31', '2015-06-06', '2015-06-13', '2015-06-20','2015-06-27','2015-07-03'];
But when I put: ticks: ticks2, my bars disappear.
My view is:
$(document).ready(function(){
var ticks2 = ['2015-05-31', '2015-06-06', '2015-06-13', '2015-06-20','2015-06-27','2015-07-03'];
var ticks = ['0.02', '0.04', '0.06', '0.08','0.1','0.12'];
$.ajax({
url: "<?= base_url() ?>index.php/receivedOrders/get_prices",
dataType:"json",
}).success(function(responseText) {
console.log(responseText)
$.jqplot.config.enablePlugins = true;
var plot2 = $.jqplot('column_chart', responseText, {
seriesDefaults:{
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barPadding: 1,
barMargin: 15,
barDirection: 'vertical',
barWidth: 50
},
pointLabels: { show: true }
},
axes: {
xaxis:{
renderer:$.jqplot.DateAxisRenderer,
// ticks: ticks2,
tickOptions: {
formatString:' %Y-%m-%d %H:%M'
//, min:'2015-06-06', max:'2015-06-30', tickInterval:'7 days'
},
},
yaxis: {
ticks: ticks,
tickOptions: {
formatString: '%.2f'
},
}
},
highlighter: {
sizeAdjust: 7.5
},
cursor: {
show: true
}
});
}
);
});

Related

Highcharts Multiple Series data - label mismatch

I have multiple series lets call them
A, B, C, D
I have pulled the series data like so
data:[1,2,3], data:[4,5,6], data[3,5,7], data[7,8,9]
The data is showing correctly on the bar chart
But when I click the series name/identifier on the y-Axis while the bar shows the correct data, the label that appears beside the bar, is incorrect.It seems to use an index based correlation between series and labels
Here is my code:
axios.get('/api/getData')
.then((response) => {
let data= response.data
//initialize series, category arrays
let series = [];
let categories = [];
//group data by product types
let productTypeGroups = _.groupBy(stockData, (product) => {
return product.type;
});
//loop through grouped data and create series for each product type
for(const[key,value] of Object.entries(productTypeGroups)){
let dataValues= _.map(value, (product)=>{
//push product names into category array
categories.push(product.name)
return product.current_balance < 0 ? 0 : product.current_balance;
})
//set default visibility to true if product is vaccine
let visibility = key === 'A' ? true : false
series.push({
name:key,
data:dataValues,
visible:visibility
})
}
this.dataValuesChart.highchartOptions.xAxis.categories = categories
this.dataValuesChart.dataValues.series = series
Here is the HighCharts Config:
highchartOptions: {
chart: {
type: 'bar',
height: 500
},
title: {
text: 'Stock Balance'
},
subtitle: {
text: ''
},
yAxis: {
title: {
text: 'Doses'
},
labels: {
format: '{value}'
}
},
xAxis: {
categories: [],
labels:{
step:1
}
},
plotOptions: {
series: {
label: {
connectorAllowed: false
}
}
},
series: [],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
}
Here is a screenshot of how the chart displays:
How does the click event know what labels to pull, should we use some sort of dynamic category setting for this to work? Is there another way to do this even?
Credit #ppoctaczek for pointing out the data array can also be a multidimensional array [x, y] as documented here: https://api.highcharts.com/highcharts/series.bar.data
In terms of hiding the unclicked series #ppoctaczek suggested I edit the plotOption section like so. NB default behaviour on click is to add or remove clicked series to already clicked series - you can retain these defaults if that works for you.
plotOptions: {
series: {
label: {
connectorAllowed: false
},
grouping:false,
events:{
legendItemClick: function(){
this.chart.series.forEach(s=>{
s.hide();
});
this.show();
return false;
}
}
}
},
Then in terms of the data array I needed to make it multidimensional, and have the x value referencing the serial indices of the categories across the multiple series. I achieved this by:
//initialize index counter
let i = 0;
//loop through grouped data and create series for each product type
for(const[key,value] of Object.entries(productTypeGroups)){
let balances = [];
_.each(value, (product)=>{
//push product names into category array
categories.push(product.name)
//push index and balance into balances array
balances.push([i, product.current_balance]);
//increment index
i++;
})
//set default visibility to true if product is vaccine
let visibility = key === 'vaccine' ? true : false
series.push({
name:key,
data:balances,
visible:visibility
})
}
Your data array on console.log your series data should look like this:

How to show grid-lines when chart data is empty, in High Stock charts?

I need to show grid lines when my chart has no data. (For now, It shows a blank division when there is no data) How to show grid lines? Is it possible to do? I tried but couldn't find an useful answer. Following is the method I used to draw the chart.
public drawChart(): void {
this.options = new StockChart ({
rangeSelector: {
selected: 0,
inputEnabled: false,
},
chart: {
type: 'spline',
},
yAxis: {
labels: {
formatter: function(): string {
return this.value + '';
},
},
opposite: false,
},
plotOptions: {
series: {
showInNavigator: true,
},
},
series: [],
});
}
To show the gridlines yAxis needs to have defined some min and max values. When series is applied those values are calculated and set to the yAxis, but in the case of the empty data, we need to apply them as the dummy values. Later, when data will be applied we can reset those values by using the yAxis.update feature.
Demo: https://jsfiddle.net/BlackLabel/zcsp8nfr/
API: https://api.highcharts.com/class-reference/Highcharts.Axis#update
API: https://api.highcharts.com/class-reference/Highcharts.Series#update

ChartJS / MomentJS - Unable to remove deprecation warning. Graph not showing in firefox/opera

so browsers throw
warning about using momentJS incorrectly.
Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 12.30, _f: false, _strict: undefined, _locale: [object Object]
Error
So i looked at my code
data: {
labels: ['01.01', '02.01', '03.01', '04.01', '05.01', '06.01', '07.01', '08.01', '09.01', '10.01', '11.01', '12.01'],
datasets: createChatterData(data, this)
},
And read that I should provide a format when dealing with non iso strings.
labels: [moment('01.01', 'MM.DD'), moment('02.01', 'MM.DD'), ...];
Ok that removed first deprecation.
But my datasets data also contains of date
dataset.data.pushObject({
x: moment(datum).format('MM.DD'),
y: parseInt(moment(datum).format('YYYY'))
});
So I tried different variations to that (premodified ambigious datetime)
x: moment(date, 'YYYY.MM.DD').format('MM.DD')
and
x: moment(date, 'MM.DD')
But my graph doesnt map correctly anymore.
Example of codepen chart working in chrome: http://codepen.io/kristjanrein/pen/wJrQLE
Does not display in firefox/opera
I see a couple of issues here.
1) Since you want your X axis to be a time scale, then you should leave your X data value as a moment object. Your current implementation is creating a moment object from a date string and then formatting it back to a string. When you do this, chart.js then takes the string and tries to create a moment object internally when it builds the chart.
Therefore, It is best to keep the data as either a Date or Moment object and use the time scale configuration properties to determine how the data is displayed on the chart. This prevents chart.js from having to construct the moment object and guess at the string format.
2) You are using the pre-2.0 way to create a chart when you use Chart.Scatter. Instead you should use the new style (new Chart()) and pass in a type property.
Here is a modified version of you code that results in no browser warnings and works in Chrome and Firefox (I did not test in Opera).
var getData = function() {
var dummyDataset = [
'2007-11-09T00:00:00.000Z',
'2006-08-04T00:00:00.000Z',
'2006-08-06T00:00:00.000Z',
'2008-01-10T00:00:00.000Z'
];
return dummyDataset.map(function(datum) {
var myMoment = moment(datum);
return {
x: myMoment,
y: parseInt(myMoment.format('YYYY')),
};
});
};
var ctx = document.getElementById("chart1").getContext("2d");
var myScatter = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "My First dataset",
borderColor: 'rgb(255, 99, 132)',
fill: false,
pointRadius: 4,
pointHoverRadius: 8,
showLine: false,
data: getData()
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Random Data'
},
legend: {
display: true,
labels: {
fontSize: 10,
boxWidth: 20
}
},
elements: {
point: {
pointStyle: 'rect'
}
},
hover: {
mode: 'nearest'
},
scales: {
xAxes: [{
type: 'time',
position: 'bottom',
scaleLabel: {
display: true,
labelString: 'Months'
},
time: {
unit: 'month',
displayFormats: {
month: 'MM'
},
}
}],
yAxes: [ {
type: 'linear',
ticks: {
min: 2005,
max: 2015,
stepSize: 1
},
scaleLabel: {
display: true,
labelString: 'Year'
}
}]
}
}
});
You can see it in action at this forked codepen.
One other thing to keep in mind is that because your data spans multiple years, you will see duplicate months on the X axis. Remember, a time scale is used to plot dates so even if you only display the months, a data point with the same month but with different years will not be plotted at the same location.
If you are actually only wanting to show month string/number values in the X axis, then you should not use the time scale at all and use the linear scale instead. Then when you build your data values, you would extract the month from the data (the same way you are already doing for your Y value).
var getData = function() {
var dummyDataset = [
'2007-11-09T00:00:00.000Z',
'2006-08-04T00:00:00.000Z',
'2006-08-06T00:00:00.000Z',
'2008-01-10T00:00:00.000Z'
];
return dummyDataset.map(function(datum) {
var myMoment = moment(datum);
return {
x: parseInt(myMoment.format('MM')),
y: parseInt(myMoment.format('YYYY')),
};
});
};
So in addition to jordan's answer
I changed my labels and x axis from
['01.01', '02.01', ...] to [1,2,...]
and
from type: 'time' to type: 'linear'
And to make it map not only by month but also by day. I had to make date objects to correct floats. 05.20 to 5.66
const date = datum.key;
const day = parseInt(moment(date).format('DD')) / 30 * 100;
const fullDate = parseFloat(moment(date).format('MM') + '.' + Math.round(day))
// 05.10 would be 5.3 (10 of 30 is 33%)
{
x: fullDate,
y: parseInt(moment(date).format('YYYY'))
date: date, // for tooltip
count: count // for tooltip
}
And i also had to make corrections to my tooltips
callbacks: {
title: function([tooltipItem], data) {
const tooltipInfo = getTooltip(tooltipItem, data.datasets);
return tooltipInfo.date;
},
label: function(tooltipItem, data) {
const tooltipInfo = getTooltip(tooltipItem, data.datasets);
return i18n.t('chart.count') + ': ' + tooltipInfo.count;
},
}
corresponding tooltip dataset
function getTooltip(tooltipItem, datasets) {
return datasets[tooltipItem.datasetIndex].data.find(datum => {
return datum.x === tooltipItem.xLabel && datum.y === tooltipItem.yLabel;
});
}

Google Charts: Horizontal Reference Line on Barchart

Having a Barchart like the following
I want to be able to draw an horizontal reference line (For example at 80%). However this doesn't seem to be possible on Google Charts.
I've tried several things, including combo charts with multiple series.
However it won't look very nice since the hAxis is discrete :(
Your help would be very appreciated.
add another series for the Reference Line
use the same value for all rows and change the series type to 'line'
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Category', 'Value', 'Reference'],
['Quant', 0.10, 0.80],
['Verbal', 0.30, 0.80],
['Total', 0.20, 0.80]
]);
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chartDiv);
chart.draw(data, {
colors: ['lime', 'magenta'],
legend: 'none',
series: {
1: {
type: 'line'
}
},
title: 'Percentile Score',
vAxis: {
format: 'percent',
viewWindow: {
min: 0,
max: 1
}
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
in the above snippet, the reference line stops at the center of the first and last columns
extend the line to the edges of the columns by changing the coordinates of the reference line,
use the 'ready' listener to know when the chart has been drawn
the key is finding the specific chart elements you need to work with,
in the following snippet, the series color is used to find the columns and reference line
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Category', 'Value', 'Reference'],
['Quant', 0.10, 0.80],
['Verbal', 0.30, 0.80],
['Total', 0.20, 0.80]
]);
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chartDiv);
// use colors to find chart elements
var colorMagenta = '#ff00ff';
var colorLime = '#00ff00';
var xBeg; // save first x coord
var xWidth; // save width of column
var rowIndex = -1; // find first column
google.visualization.events.addListener(chart, 'ready', function () {
// columns
Array.prototype.forEach.call(chartDiv.getElementsByTagName('rect'), function(rect, index) {
if (rect.getAttribute('fill') === colorLime) {
rowIndex++;
xWidth = parseFloat(rect.getAttribute('width')) / 2;
if (rowIndex === 0) {
xBeg = parseFloat(rect.getAttribute('x'));
}
}
});
// reference line
Array.prototype.forEach.call(chartDiv.getElementsByTagName('path'), function(path, index) {
if (path.getAttribute('stroke') === colorMagenta) {
// change line coords
var refCoords = path.getAttribute('d').split(',');
refCoords[0] = 'M' + xBeg;
var refWidth = refCoords[2].split('L');
refWidth[1] = parseFloat(refWidth[1]) + xWidth;
refCoords[2] = refWidth.join('L');
path.setAttribute('d', refCoords.join(','));
}
});
});
chart.draw(data, {
colors: [colorLime, colorMagenta],
legend: 'none',
series: {
1: {
type: 'line'
}
},
title: 'Percentile Score',
vAxis: {
format: 'percent',
viewWindow: {
min: 0,
max: 1
}
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How can I add a title to c3.js chart

Can any one suggest me the way of adding title to the C3.js line and bar charts ? I have got the following sample but it is for gauge chart. For any c3 chart is there any option to set the chart title?
donut: {
title: 'Title'
}
This was a top google result, so I thought I'd add that this is now part of the library:
title: {
text: 'My Title'
}
More info # https://github.com/masayuki0812/c3/pull/1025
You'd need to fall back to using D3 to add a chart title. Something like:
d3.select("svg").append("text")
.attr("x", 100 )
.attr("y", 50)
.style("text-anchor", "middle")
.text("Your chart title goes here");
I am using this code for my chart.
Code:
var chart = c3.generate({
data: {
columns: [
['Monday', 70],
['TuesDay', 20],
['Wednesday', 30],
['Thursday', 50],
['Friday', 100]
],
type: 'donut'
},
donut: {
title: "usage "
}
});
Result :
also couldn't find a way and ended up writing the title as the unit and editing the label.
gauge: {
label: {
format: function(value, ratio) {
return "%"+value;
},
show: true // to turn off the min/max labels.
},
min: 0,
max: 100,
units: "Overall Profit"
// width: 39 // for adjusting arc thickness
},