How can I hide the lines that go below value 1 so the chart doesn't look like the one below?. My chart shows a product sales over period of time. Some products don't have enought data which produces weirdly looking charts.
I have added vAxis: { viewWindowMode: 'pretty' } and this is helping to some extent to make it "pretty" but it isn't enough.
I've tried with data view and I thought that was the solution but the view is hiding some extra rows. My code for view where I convert the 0 row to date and trying to limit the min and max values:
let view = new google.visualization.DataView(dataYear);
view.setColumns([{
calc: function(dataYear, row) {
return new Date(dataYear.getValue(row, 0));
},
label: dataYear.getColumnLabel(0),
type: 'date'
}, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
view.setRows(view.getFilteredRows([{
column: 1,
minValue: 1,
maxValue: 500
}]));
I am a bit confused how view exactly works after many tries of tweaking up different columns and min/maxValues. In addition, I can target only 1 column at a time with the view? Bonus question: I would like also to hide the data points that are with 0 value (the one appearing on the x axis)
My chart code:
function chartYear(dataYear) {
// Display the total number of products sold for each chart/period
function getSum(dataYear, column) {
var total = 0;
for (i = 0; i < dataYear.getNumberOfRows(); i++)
total = total + dataYear.getValue(i, column);
return total;
}
let name = document.querySelectorAll('.google-visualization-table-tr-sel td')[2].textContent;
let interval = 1;
let dataRange = dataYear.getColumnRange(9);
let vTicks = [];
for (var i = dataRange.min; i <= dataRange.max + interval; i = i + interval) {
vTicks.push(i);
};
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chartYear',
options: {
title: "6 months sales: " + name + "\nTotal: " + getSum(dataYear, 9),
curveType: "function",
pointsVisible: true,
pointSize: 5,
snapToData: true,
// pointBackgroundColor: '#FF0000',
titleTextStyle: {
fontName: 'Verdana',
fontSize: 13,
italic: true
},
vAxis: {
viewWindowMode: 'pretty',
ticks: vTicks,
minValue: 1
},
hAxis: {
// minValue: 1, // THROWS ERROR a.getTime() is not a function
// viewWindowMode: 'pretty',
slantedText: 1,
slantedTextAngle: 60
},
series: {
0: {
color: '#DC3912'
},
1: {
color: '#FF9900'
},
2: {
color: '#109618'
},
3: {
color: '#990099'
},
4: {
color: '#bbe9ff'
},
5: {
color: '#43459d'
},
6: {
color: '#C60AD3'
},
7: {
color: '#1c91c0'
},
8: {
color: '#3366CC'
},
}
}
});
var dateSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'chartRangeFilter',
'options': {
filterColumnLabel: 'Dato',
ui: {
chartType: 'LineChart',
chartOptions: {
snapToData: true,
height: 50,
chartArea: {
width: '80%'
},
series: {
0: {
color: '#DC3912'
},
1: {
color: '#FF9900'
},
2: {
color: '#109618'
},
3: {
color: '#990099'
},
4: {
color: '#bbe9ff'
},
5: {
color: '#43459d'
},
6: {
color: '#C60AD3'
},
7: {
color: '#1c91c0'
},
8: {
color: '#3366CC'
},
}
}
}
}
});
var formatter_long = new google.visualization.DateFormat({
pattern: 'yyyy-MM-dd'
});
formatter_long.format(dataYear, 0);
google.visualization.events.addListener(chart, 'error', function(googleError) {
google.visualization.errors.removeError(googleError.id);
});
let view = new google.visualization.DataView(dataYear);
view.setColumns([{
calc: function(dataYear, row) {
return new Date(dataYear.getValue(row, 0));
},
label: dataYear.getColumnLabel(0),
type: 'date'
}, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
view.setRows(view.getFilteredRows([{
column: 1,
minValue: 0,
maxValue: 500
}]));
var dashboard2 = new google.visualization.Dashboard(document.getElementById('dashboard2'));
dashboard2.bind(dateSlider, chart);
dashboard2.draw(view);
}
The chart is drawn when the user clicks on a table row. I send the product id with ajax and get back data for this product. I can add the select handler if needed.
Related
I am displaying pie-chart as a tootip inside a column chart using google charts.
In the pie-chart, I want to do legend: { position: 'labeled' }, but it is not displaying the bars of the Column chart, and so cannot display the Pie chart.
It is only displaying the gridlines.
My current code:
//Create Charts
function AggregateCharts(aggregateResult){
$('#hidden_div').show();
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback( function(){ drawTooltipCharts(aggregateResult) });
}
// Draw tool tip charts
function drawTooltipCharts(aggregateResult) {
//set bar chart data
primaryData=[];
if(aggregateResult){
aggregateResult.map(data=>{
if(data.Count>0 || data.High>0 || data.Medium>0)
{
//Set Options
var tooltipOptions = {
title: 'Data Title',
isStacked: true,
pieHole: 0.4,
sliceVisibilityThreshold:0,
colors: ['#c1c1c1','#0074AA','#1DB2F7','#F7941D' ],
legendTextStyle: { color: '#1DB2F7' ,fontSize: 12},
titleTextStyle: { color: '#1DB2F7', alignment: 'center',fontSize: 15},
chartArea: {width:510, height: 250} ,
legend: { position: 'labeled' },
pieStartAngle: 100,
pieSliceTextStyle: { fontSize:12 },
};
//Create chart View
var view = new google.visualization.DataTable();
view.addColumn('string', 'Criteria');
view.addColumn('number', 'Users');
var total=total;
var Count=data.Count;
var High=data.High;
var Medium=data.Medium;
//calculation part
var Countpercentage =((Count/total).toFixed(2))*100;
var Highpercentage =((High/total).toFixed(2))*100;
var Mediumpercentage =((Medium/total).toFixed(2))*100;
var NoCriteriaEndorsed= 100-(Math.floor(Countpercentage) + Math.floor(Highpercentage) + Math.floor(Mediumpercentage) );
var tooltipData=[];
tooltipData.push(["No Criteria Endorsed",NoCriteriaEndorsed]);
tooltipData.push(["50-69% Criteria Endorsed",Mediumpercentage]);
tooltipData.push(["70-99% Criteria Endorsed",Highpercentage]);
tooltipData.push(["100% Criteria Endorsed",Countpercentage]);
//Add total rows
view.addRows(tooltipData);
var hiddenDiv = document.getElementById('hidden_div');
var tooltipChart = new google.visualization.PieChart(hiddenDiv);
google.visualization.events.addListener(tooltipChart, 'ready', function() {
// Get the PNG of the chart and set is as the src of an img tag.
var tooltipImg = '<img src="' + tooltipChart.getImageURI() + '">';
// Add the new tooltip image to your data rows.
primaryData.push([data.Diagnosis,data.Count,tooltipImg,data.High,tooltipImg,data.Medium,tooltipImg]);
});
tooltipChart.draw(view, tooltipOptions);
}
})
//Create bar chart
drawBarChart(primaryData);
}
}
function drawBarChart(primaryData) {
var fromDate=$("#fromdate").val()?$("#fromdate").val():getMinDate(AggregateData)
var tooltipData = new google.visualization.DataTable();
tooltipData.addColumn('string', 'Event');
tooltipData.addColumn('number', '100% Criteria Endorsed');
// Add a new column for your tooltips.
tooltipData.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
tooltipData.addColumn('number', '70-99% Criteria Endorsed');
// Add a new column for your tooltips.
tooltipData.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
tooltipData.addColumn('number', '50-69% Criteria Endorsed');
// Add a new column for your tooltips.
tooltipData.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
// Add your data (with the newly added tooltipImg).
tooltipData.addRows(primaryData);
var minwidth=tooltipData.getNumberOfRows() <25 ?(25*50) : tooltipData.getNumberOfRows() *50;
var primaryOptions = {
title: 'Results' ,
legend: 'none',
tooltip: {isHtml: true},
isStacked: true,
colors: ['#F7941D', '#1DB2F7', '#0074AA'],
legendTextStyle: { color: '#000000' , fontSize: 20 },
titleTextStyle: { color: '#000000', fontSize: 16, fontName: 'Calibri Light', bold: true },
width: minwidth,
bar: {groupWidth:15},
hAxis: {
textStyle: { color: "#1DB2F7" ,fontSize: 8, bold: true },
gridlines: { count: 4, color: "#1DB2F7" },
baselineColor: '#1DB2F7',
},
vAxis: {
title: 'Number of Respondents',
titleTextStyle: { color: '#000000', fontSize: 18, fontName: 'Calibri Light', bold: true},
textStyle: { color: "#1DB2F7", fontSize: 10, bold: true },
gridlines: { count: 4 , color: "#1DB2F7" },
baselineColor: '#1DB2F7' ,
},
};
var visibleDiv = document.getElementById('visible_div');
var primaryChart = new google.visualization.ColumnChart(visibleDiv);
primaryChart.draw(tooltipData, primaryOptions);
CustomOptions(primaryOptions);
var btndownloadchart = document.getElementById('downloadchart');
btndownloadchart.addEventListener('click', function () {
this.href= primaryChart.getImageURI();
}, false);
}
//Date format to display in chart legend
function dateFormat(requestDate){
var date = requestDate?new Date(requestDate):new Date();
var dateString =date.toLocaleString('en', { month: 'long' })+" "+ date.getDate() +", "+ date.getFullYear() ;
return dateString;
}
//get mindate value for aggregate if from date not selected initially..
function getMinDate(AggregateData){
if(AggregateData){
var minDate = Math.min.apply(null, AggregateData.map(function(o) { return new Date(o.CreatedDate); }))
return date = new Date(minDate)
}
return new Date()
}
function CustomOptions(primaryOptions) {
var $container = $('#visible_div');
var svg = $container.find('svg') ;
var svgWidth=$container.find('svg').width();
var $titleElemWidth = parseInt($container.find('svg').width()/8) ;
var svgMargin= ('-' +((svgWidth/15)>170?170:(svgWidth/15))+ 'px');
svg.css("margin-left", svgMargin);
var $titleElem = $container.find("text:contains(" + primaryOptions.vAxis.title +")");
$titleElem.attr('y',$titleElemWidth<320?320:$titleElemWidth);
//Hide tooltip chart
$('#hidden_div').hide();
}
]]>
When I do legend: { alignment: 'center' } in the 'tooltipOptions', the Column chart and the Pie-chart is displaying correctly.
But I want to do 'legend: { position: 'labeled' }', as the Pie-Chart slices is not displaying the percentage for small values.
Try passing the following to your options:
pieSliceTextStyle: {
color: 'white',
fontSize: '13',
top: 10,
left: 50,
position: 'start',
},
I have a category filtering combochart, which is perfectly working with the following code:
var columnsTable = new google.visualization.DataTable();
columnsTable.addColumn('number', 'colIndex');
columnsTable.addColumn('string', 'colLabel');
var initState= {selectedValues: []};
// put the columns into this data table (skip column 0)
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
// you can comment out this next line if you want to have a default selection other than the whole list
initState.selectedValues.push(data.getColumnLabel(i));
}
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'myPieChart2',
dataTable: data,
options: {
height: 300,
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Flight Hours (min)'
},
title: 'Annual Flight Times by Pilot',
bar: {groupWidth: '90%'},
seriesType: 'bars',
series: {
0: {type: 'line',
lineDashStyle: [4, 4]},
1: {type: 'line',
lineDashStyle: [14, 2, 2, 7]},
}
//theme: 'material'
}
});
var columnFilter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'colFilter_div2',
dataTable: columnsTable,
options: {
filterColumnLabel: 'colLabel',
ui: {
label: 'Pilots',
allowTyping: false,
allowMultiple: true,
allowNone: false,
//selectedValuesLayout: 'belowStacked'
}
},
state: initState
});
function setChartView () {
var state = columnFilter.getState();
var row;
var view = {
columns: [0]
};
for (var i = 0; i < state.selectedValues.length; i++) {
row = columnsTable.getFilteredRows([{column: 1, value: state.selectedValues[i]}])[0];
view.columns.push(columnsTable.getValue(row, 0));
}
// sort the indices into their original order
view.columns.sort(function (a, b) {
return (a - b);
});
chart.setView(view);
chart.draw();
}
google.visualization.events.addListener(columnFilter, 'statechange', setChartView);
setChartView();
columnFilter.draw();
});
In my data, first two columns (Series 0 and Series 1) belongs to Total and Average of the relevant months. So, I would like to make them constant, which means that they can not be closed (See the image).
Alternatively, if there is a method to exclude them from dropdown & filtering options, but still show at the chart, this can be accepted. In the end, I would like to prevent user to close these items.
How can I do that? I spent two hours for it but still I am stucked.
Thanks for your help in advance.
I have a Google combo chart that has one value as bars and one value for a line, I also wanted a line to show the average of the value of the bars, so I found code that would do that, however, when implemented my other line disappeared.
This is what my chart looked like prior.
And this is after I implemented the average line, my other line disappeared.
I don't know how to do to make them both show?
This line seems to have things to do with all of it, changing dv back to data will show how my chart looked like on the first picture, but I guess there is something more I need to change to make it all work?
chart.draw(dv, options);
Here is the code.
<script>
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Day', 'Repetitions', 'Sets'],
#foreach (var c in db.Query(Query, inputDate, endDate, baselift))
{
var totAvg = c.avg;
var allReps = c.reps;
var realAvg = (totAvg / allReps) * 100;
//Writes out the data that will be shown in the chart.
<text>['#c.date', #c.reps, #c.sets],</text>
}
]);
// Create a DataView that adds another column which is all the same (empty-string) to be able to aggregate on.
var viewWithKey = new google.visualization.DataView(data);
viewWithKey.setColumns([0, 1, {
type: 'string',
label: '',
calc: function (d, r) {
return ''
}
}])
// Aggregate the previous view to calculate the average. This table should be a single table that looks like:
// [['', AVERAGE]], so you can get the Average with .getValue(0,1)
var group = google.visualization.data.group(viewWithKey, [2], [{
column: 1,
id: 'avg',
label: 'Average',
aggregation: google.visualization.data.avg,
'type': 'number'
}]);
// Create a DataView where the third column is the average.
var dv = new google.visualization.DataView(data);
dv.setColumns([0, 1, {
type: 'number',
label: 'Average',
calc: function (dt, row) {
return group.getValue(0, 1);
}
}]);
var options = {
title: 'Daily Repetition Statistics',
backgroundColor: { fill: 'transparent' },
explorer: { axis: 'horizontal' },
vAxes: {
0: { logScale: false, viewWindow: { min: 0 } },
1: { logScale: false, maxValue: 2 }
},
hAxis: { title: 'Day' },
seriesType: 'bars',
curveType: 'function',
series: {
0: {
targetAxisIndex: 0,
color: 'orange'
},
1: { targetAxisIndex: 1 },
1: { targetAxisIndex: 1, type: "line" },
2: { targetAxisIndex: 1, type: "line" }
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(dv, options);
}
</script>
the column index for 'sets' is not provided to setColumns
change this...
var dv = new google.visualization.DataView(data);
dv.setColumns([0, 1, {
type: 'number',
label: 'Average',
calc: function (dt, row) {
return group.getValue(0, 1);
}
}]);
to..
var dv = new google.visualization.DataView(data);
dv.setColumns([0, 1, 2, { // <-- add 'sets' column index 2
type: 'number',
label: 'Average',
calc: function (dt, row) {
return group.getValue(0, 1);
}
}]);
Using Google Charts API, I have made a line chart. Is there any way to be able to shade between two vertical lines? I know I most likely have to use a combo chart, but can anyone make a simple jsfiddle of an Area Chart that shades the middle of two vertical lines? Thank you!
following is a snippet that draws a bell curve based on the input range.
vertical lines are drawn to identify the Mean and Standard Deviation ranges.
shading is added to highlight the areas within 1, 2, & 3 Standard Deviations from the Mean.
google.charts.load('43', {
callback: function () {
document.getElementById('range-draw').addEventListener('click', loadBellCurve, false);
window.addEventListener('resize', loadBellCurve, false);
loadBellCurve();
},
packages:['controls', 'corechart']
});
function loadBellCurve() {
// build data sample
var rangeMin = parseInt(document.getElementById('range-min').value);
var rangeMax = parseInt(document.getElementById('range-max').value);
var step = 0.05;
var dataChart = new google.visualization.DataTable({
cols: [
{label: 'Sample', type: 'string'},
{label: 'Value', type: 'number'},
{label: 'Var', type: 'number'},
{label: 'X', type: 'number'},
{label: 'Y', type: 'number'}
]
});
for (var i = rangeMin; i <= rangeMax; i=i+step) {
dataChart.addRow([i.toString(), i, null, null, null]);
}
// find sample mean
var dataMean = google.visualization.data.group(
dataChart,
[{column: 0, type: 'string', modifier: function () {return '';}}],
[{column: 1, type: 'number', aggregation: google.visualization.data.avg}]
);
var sampleMean = dataMean.getValue(0, 1);
// find sample standard deviation
for (var i = 0; i < dataChart.getNumberOfRows(); i++) {
dataChart.setValue(i, 2, Math.pow(dataChart.getValue(i, 1) - sampleMean, 2));
}
var dataVar = google.visualization.data.group(
dataChart,
[{column: 0, type: 'string', modifier: function () {return '';}}],
[{column: 2, type: 'number', aggregation: google.visualization.data.avg}]
);
var sampleStdDev = Math.sqrt(dataVar.getValue(0, 1));
// set standard deviation ranges 1-3
var sampleRange = [];
sampleRange.push([
sampleMean - sampleStdDev,
sampleMean + sampleStdDev
]);
sampleRange.push([
sampleMean - (sampleStdDev * 2),
sampleMean + (sampleStdDev * 2)
]);
sampleRange.push([
sampleMean - (sampleStdDev * 3),
sampleMean + (sampleStdDev * 3)
]);
// set X/Y coordinates
for (var i = 0; i < dataChart.getNumberOfRows(); i++) {
dataChart.setValue(i, 3, dataChart.getValue(i, 1) * sampleStdDev + sampleMean);
dataChart.setValue(i, 4, getNormalDistribution(dataChart.getValue(i, 1) * sampleStdDev + sampleMean, sampleMean, sampleStdDev));
}
// fill-in standard deviation areas
var stdDevCols = {};
stdDevCols['1_SD'] = dataChart.addColumn({label: '1 Std Dev', type: 'number'});
stdDevCols['2_SD'] = dataChart.addColumn({label: '2 Std Dev', type: 'number'});
stdDevCols['3_SD'] = dataChart.addColumn({label: '3 Std Dev', type: 'number'});
for (var i = Math.floor(sampleRange[2][0]); i <= Math.ceil(sampleRange[2][1]); i=i+0.05) {
var rowIndex = dataChart.addRow();
dataChart.setValue(rowIndex, 3, i);
if (((i) >= sampleRange[0][0]) && ((i) < sampleRange[0][1])) {
dataChart.setValue(rowIndex, stdDevCols['1_SD'], getNormalDistribution(i, sampleMean, sampleStdDev));
} else if (((i) >= sampleRange[1][0]) && ((i) < sampleRange[1][1])) {
dataChart.setValue(rowIndex, stdDevCols['2_SD'], getNormalDistribution(i, sampleMean, sampleStdDev));
} else {
dataChart.setValue(rowIndex, stdDevCols['3_SD'], getNormalDistribution(i, sampleMean, sampleStdDev));
}
}
// add vertical lines for mean and standard deviations
addVerticalLine('MEAN', sampleMean);
addVerticalLine('< 1 SD', sampleRange[0][0]);
addVerticalLine('> 1 SD', sampleRange[0][1]);
addVerticalLine('< 2 SD', sampleRange[1][0]);
addVerticalLine('> 2 SD', sampleRange[1][1]);
// series options
var markersArea = {
enableInteractivity: false,
pointsVisible: false,
tooltip: false,
type: 'area'
};
var markersLine = {
enableInteractivity: false,
lineWidth: 3,
pointsVisible: false,
tooltip: false,
type: 'line',
visibleInLegend: false
};
// combo chart
var chartCombo = new google.visualization.ChartWrapper({
chartType: 'ComboChart',
containerId: 'chart-combo',
options: {
animation: {
duration: 1000,
easing: 'linear',
startup: true
},
colors: ['#1565C0', '#43A047', '#FFB300', '#E53935', '#43A047', '#FFB300', '#FFB300', '#E53935', '#E53935'],
explorer: { actions: ['dragToZoom', 'rightClickToReset'] },
hAxis: {
format: '#,##0'
},
height: 340,
legend: {
textStyle: {
color: '#676767',
fontSize: 10
}
},
series: {
0: {
pointShape: {
type: 'star',
sides: 4,
dent: 0.3
},
pointSize: 12,
pointsVisible: true,
type: 'scatter'
},
1: markersArea,
2: markersArea,
3: markersArea,
4: markersLine,
5: markersLine,
6: markersLine,
7: markersLine,
8: markersLine
},
seriesType: 'scatter',
theme: 'maximized',
title: 'Normal Distribution',
titleTextStyle: {
color: '#676767',
bold: false,
fontSize: 10
},
tooltip: {
isHtml: true
},
vAxis: {
format: '#,##0.0000'
},
width: '100%'
}
});
// range filter
var controlRangeFilter = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'chart-control-range',
options: {
filterColumnIndex: 0,
ui: {
chartType: 'AreaChart',
chartOptions: {
annotations: {
highContrast: false,
stem: {
color: 'transparent',
length: 0
},
textStyle: {
color: 'transparent'
}
},
chartArea: {
left: 0,
width: '100%'
},
colors: ['#1565C0', '#43A047', '#FFB300', '#E53935', '#43A047', '#FFB300', '#FFB300', '#E53935', '#E53935'],
height: 72,
width: '100%'
}
}
}
});
// chart data view
var viewChart = new google.visualization.DataView(dataChart);
viewChart.setColumns([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]);
// draw dashboard
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
dashboard.bind(controlRangeFilter, chartCombo);
dashboard.draw(viewChart);
function getNormalDistribution(x, Mean, StdDev) {
return Math.exp(-((x - Mean) * (x - Mean)) / (2 * StdDev * StdDev)) / (Math.sqrt(2 * Math.PI) * StdDev);
}
function addVerticalLine(colLabel, xVal) {
var yCol = dataChart.addColumn({label: colLabel, type: 'number'});
var annCol = dataChart.addColumn({role: 'annotation', type: 'string'});
var rowIndex = dataChart.addRow();
dataChart.setValue(rowIndex, 3, xVal);
dataChart.setValue(rowIndex, yCol, getNormalDistribution(xVal, sampleMean, sampleStdDev));
dataChart.setValue(rowIndex, annCol, xVal.toFixed(2) + ' %');
rowIndex = dataChart.addRow();
dataChart.setValue(rowIndex, 3, xVal);
dataChart.setValue(rowIndex, yCol, 0);
}
}
input {
font-family: Arial;
font-size: 10px;
}
input[type=number] {
text-align: right;
width: 48px;
}
label {
font-family: Arial;
font-size: 10px;
font-weight: bold;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard">
<div>
<label for="range-min">Min:</label> <input type="number" id="range-min" value="-4" />
<label for="range-max">Max:</label> <input type="number" id="range-max" value="4" />
<input type="button" id="range-draw" value="Draw Chart" />
</div>
<div id="chart-combo"></div>
<div id="chart-control-range"></div>
<div id="chart-table"></div>
</div>
I have a chart with ordering by date.
My problem is the chart lines joining false from start to end.
My options:
var options =
{
grid:
{
color: "#dedede",
borderWidth: 1,
borderColor: "transparent",
clickable: true,
hoverable: true
},
series: {
grow: {active:false},
lines: {
show: true,
fill: false,
lineWidth: 2,
steps: false
},
points: {
show:true,
radius: 5,
lineWidth: 3,
fill: true,
fillColor: "#000"
}
},
legend: { position: "nw", backgroundColor: null, backgroundOpacity: 0, noColumns: 2 },
yaxis: { tickSize:50 },
xaxis: {
mode: "time",
tickFormatter: function(val, axis) {
var d = new Date(val);
return d.getUTCDate() + "/" + (d.getUTCMonth() + 1);
}
},
colors: [],
shadowSize:1,
tooltip: true,
tooltipOpts: {
content: "%s : %y.0",
shifts: {
x: -30,
y: -50
},
defaultTheme: false
}
};
Note: I'm not re-ordering any data. Just giving the timestamp with this function:
function gd(year, month, day) {
return new Date(year, month - 1, day).getTime();
}
Setting the data like this:
$.each(e.data, function(i, e){
data.push([gd(parseInt(e['year']), parseInt(e['month']), parseInt(e['day'])), parseInt(e['value'])]);
});
var entity = {
label: e.campaign,
data: data,
lines: {fillColor: randomColor},
points: {fillColor: randomColor}
};
entities.push(entity);
Console log:
When creating line charts, flot will connect the data points using the order from the data series, ignoring the actual x-coordinates. That's why data series should be in ascending order.
A minimal example (using your data in ascending order):
var d1 = [
[1401310800000, 275],
[1401397200000, 270],
[1401483600000, 313],
[1401570000000, 279],
[1401656400000, 216],
[1401742800000, 255],
[1401829200000, 244],
[1401915600000, 70]
];
$.plot("#chart", [ d1 ]);
Here is a jsfiddle showing the chart.