I just got a book called Data Visualization With Javascript by Stephen A. Thomas, and I'm working through the exercises. The first chapter is on Flotr2. Here is what the book told me to do:
var wins = [[[0, 13], [1, 11], [2, 15], [3, 15], [4, 18], [5, 21], [6, 28]]];
var wins2 = [[[0,28], [1,28], [2, 21], [3,20], [4,19]]];
var years = [[0, "2006"], [1, "2007"], [2, "2008"], [3, "2009"], [4, "2010"], [5, "2011"], [6, "2012"]];
var teams = [[0, "MCI"], [1, "MUN"], [2, "ARS"], [3, "TOT"], [4, "NEW"]];
window.addEventListener('load', function() {
Flotr.draw(document.getElementById('chart2'), wins2, {
title: "Premier League Wins (2011-2012)",
colors: ['#89afd2', '#1d1d1d', '#df021d', '#0e204b', '#e67840'],
bars: {
show: true,
barWidth: 0.5,
shadowSize: 0,
fillOpacity: 1,
lineWidth: 0
},
yaxis: {
min: 0,
tickDecimals: 0
},
xaxis: {
ticks: teams
},
grid: {
horizontalLines: false,
verticalLines: false
}
});
});
Now the only difference between this and what was in the book is that the book told me to do window.onload, and I used addEventListener instead. The book says that this should make a bar graph with multiple colors (the colors listed) but all my bars are the same color, which is the first color listed. I've tried everything, but nothing seems to make it work. Has anyone else encountered this problem with Flotr2? I'm using the latest version, so is it just a problem with Flotr2 that's new since the book came out? Or am I doing something wrong?
try this.
var wins2 = [[[0,28]],[[1,28]],[[2,21]], [[3,20]],[[4,19]]];
I think it may have to do with your arrays...
var wins2 = [[[0,28], [1,28], [2, 21], [3,20], [4,19]]];
That makes an array of 1 array that has 4 arrays. So flotr is seeing you only have 1 index, which is why it uses just 1 color.
try
var wins2 = [[0,28], [1,28], [2, 21], [3,20], [4,19]];
Related
In my dygraphs chart, I have a series which has been extrapolated. I would like to color the extrapolated parts differently, but have not found a way to do that.
I suspect a way does not exist (since what I found in the documentation suggests color is per-series only), but in case there is a way, how can I change the color of a data series partway through?
You're quite right — there is no way to change the color of a part of a data series in Dygraphs. But it could be done using a separate series for extrapolated data like the following:
[
[1, 0, null],
[2, 2, null],
[3, 4, null],
[4, 6, 6],
[5, null, 8],
[6, null, 10],
[7, null, 12],
[8, null, 14],
]
var g = new Dygraph(
document.getElementById("g"), [
[1, 0, null],
[2, 2, null],
[3, 4, null],
[4, 6, 6],
[5, null, 8],
[6, null, 10],
[7, null, 12],
[8, null, 14],
], {
colors: ['green', 'red'],
labels: ['x', 'normal', 'extrapolated'],
strokeWidth: 3,
title: 'different series for extrapolated data'
});
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<div id="g"></div>
I have some problems to show some values in bars. I want a chart like this: Example. I don't know what I'm missing in here.
$('#myModalChart').on('shown.bs.modal', function (e) {
var data = [{
label: "Foo",
data: [
[2],
[3, 9, 12],
[6, 0, 3],
[9, 11, 12],
[12, 0, 1],
[15, 0, 2],
[18],
[3, 12, 12],
[9, 12, 12]
]
},
{
label: "Bar",
data: [
[2],
[3, 0, 5],
[6, 3, 7],
[9, 4, 11],
[12, 1, 3],
[15, 2, 5],
[18]
]
},
{
label: "Tree",
data: [
[2],
[3, 5, 9],
[6, 7, 15],
[9, 0, 4],
[12, 3, 13],
[15, 5, 17],
[15, 17, 17],
[12, 13, 13],
[6, 15, 15],
[18]
]
},];
var options = {
series: {
bars: {
show: true,
barWidth: 1
}
},
xaxis: {
align: "center",
ticks: [
[3.5, 'text1'],
[6.5, 'text2'],
[9.5, 'text3'],
[12.5, 'text4'],
[15.5, 'text5']
]
}
};
var plot = $.plot("#chart2", data, options)
});
I want a chart like this, with labels in it. And I wish have in all of them.
What I'm missing?
You have to create and place the data value labels yourself. How to do this can be seen in this answer.
I created a fiddle adjusting it to your code. Only the first data series (foo) has labels for now. you will have to adjust the position. The relevant code:
$.each(plot.getData()[0].data, function (i, el) {
if (el.length > 1) {
var o = plot.pointOffset({
x: el[0],
y: el[1]
});
$('<div class="data-point-label">' + el[1] + '</div>').css({
position: 'absolute',
left: o.left + 4,
top: o.top,
'text-align': 'center',
display: 'none'
}).appendTo(plot.getPlaceholder()).fadeIn('slow');
}
});
But you may also have to cleanup your data. You have multiple data points with the same x values (which means bars behind / in front of each other which leads to some being invisible). Take a look at the side-by-side and stack plugins on the flot plugin page.
If I have an array like so:
var phpintojsArray = [["1","20"]];
and... I also have a multid-array:
var data = [[1,20], [4, 20], [7, 55], [9, 10], [9, 10]];
how to add the phpintojsArray into the data array? I want:
var data = [[phpintojsArray], [1,20], [4, 20], [7, 55], [9, 10], [9, 10]];
What is one way to accomplish this?
Clarification -- Trying to manipulate the data in a chart
This works:
/* Bar Chart */
var data = [[1, 10],[3, 60], [5, 20], [7, 50], [9, 10]];
// Initialize Bars Chart
$.plot(BarChart, [
{ data: data, bars: { show: true, fillColor: { colors: [{ opacity: 1 }, { opacity: 1 }] } }, label: 'Example label' } ],
{
legend: {
backgroundColor: '#f6f6f6',
backgroundOpacity: 0.8
},
colors: ['#39d5db'],
grid: {
borderColor: '#cccccc',
color: '#999999',
labelMargin: 10
},
yaxis: {
ticks: 5
},
xaxis: {
tickSize: 1
}
}
);
This does Not work:
var phpintojsArray = <?= json_encode($sales); ?>;
var two = [3, 60];
var three = [5, 20];
var four = [7, 50];
var five = [9, 10];
/* Bars Chart */
var data = [[phpintojsArray], [two], [three], [four], [five]];
// Initialize Bars Chart
$.plot(BarChart, [
{ data: data, bars: { show: true, fillColor: { colors: [{ opacity: 1 }, { opacity: 1 }] } }, label: 'Example label' } ],
{
legend: {
backgroundColor: '#f6f6f6',
backgroundOpacity: 0.8
},
colors: ['#39d5db'],
grid: {
borderColor: '#cccccc',
color: '#999999',
labelMargin: 10
},
yaxis: {
ticks: 5
},
xaxis: {
tickSize: 1
}
}
);
Why?
You can use splice to insert the elements:
data.splice(0, 0, phpintojsArray);
This works:
/* Bar Chart */
var data = [[1, 10],[3, 60], [5, 20], [7, 50], [9, 10]];
This does Not work:
/* Bars Chart */
var data = [[phpintojsArray], [two], [three], [four], [five]];
Why?
Because the two expressions yield different structures. In the first one you have two levels of nested arrays (small arrays inside a big one). In the second you have three levels of nested arrays.
A simple console.log will show you the difference.
Make sure that your data is in the correct structure. Change it to:
var data = [two, three, four, five];
(In case it's still not clear, the brackets [] define a new array)
Regarding your question on how to prepend phpintojsArray, you could do:
Array.prototype.unshift.apply(data, phpintojsArray);
You could use eval in javascript.
For Example:
var data = [[eval("phpintojsArray")], [eval("two")], [eval("three")], [eval("four")], [eval("five")]];
I have a problem with jQuery flot.
PHP output (not JSON):
[[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]]
jQuery call:
$.ajax({
url: 'xxx.php',
success: function (data) {
var dataArray = data.split('~~'),
dataArray1 = dataArray[0],
dataArray2 = dataArray[1],
plot = $.plot($('#xxx'), [{
data: dataArray1,
color: colours[0]
},
{
data: dataArray2,
color: colours[1],
points: {
show: true,
}
},
], {
series: {
bars: {
show: true,
barWidth: .6,
align: 'center'
}
},
grid: {
show: true,
hoverable: true,
clickable: true,
autoHighlight: true,
borderWidth: true,
borderColor: 'rgba(255, 255, 255, 0)'
},
xaxis: {
show: false
}
});
}
});
Taking the data in this way, I'm trying to use jQuery Flot but does not work...
Whereas, I can by separating data:
First label:
[[1, 153], [2, 513], [3, 644]]
Second label:
[[1, 1553], [2, 1903], [3, 2680]]
I'll share a Simple example jquery Flot with ajax for basic understanding purpose.
See this page and let change it into ajax : http://www.jqueryflottutorial.com/making-first-jquery-flot-line-chart.html
First, you must successful showing the chart as described without ajax. Don't forget to put height and width in div tag if you don't include css file.:
<div id="flot-placeholder" style="width: 100%; height: 260px"></div>
If ok, then follow this step.
STEP 1 : Put the script inside a function:
<script>
function show_chart(data) {
// this will be moved to php file
//var data = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
var dataset = [{label: "line1",data: data}];
var options = {
series: {
lines: { show: true },
points: {
radius: 3,
show: true
}
}
};
$(document).ready(function () {
$.plot($("#flot-placeholder"), dataset, options);
});
}
</script>
STEP 2 : Create sample.php.
<?php
require 'config.php';
if($_POST)
{
$id = $_POST['id'];
$arr = array();
$arr = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
echo json_encode($arr);
}?>
Note : $arr that moved from the first script then become only a sample data. You should make a php class or function that fetch data from database and return as array format as shown in $arr.
STEP 3 : Create simple ajax to get the response and render the chart :
var id = 1;
$.post('/..if any folder../sample.php', {
id : id,
}, function(response){
var data = JSON.parse(response);
show_chart(data); // call function and render the chart in <div id="flot-placeholder"></div>
});
Step Finish.
In some cases, we may need two or more data type. Then just add this to the code :
inside sample.php :
$arr1 = array();
$arr2 = array();
$arr1 = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
$arr2 = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
// put more if rquired
echo json_encode($arr1,$arr2); // put more array if required
inside ajax :
var data = JSON.parse(response);
var result1 = data[0]; // response data from $arr1
var result2 = data[1]; // response data from $arr2
Sorry for long description. Hope it will help.
Just for fun :
Some people don't want to show 'sample.php' in the console log. For this purpose we can simply change 'sample' as a folder and create index.php inside it and in the ajax we just direct the url to the folder like this :
$.post('/..if any folder../sample/'), { // this will open index.php
You have recieved a string that was not qualified as JSON data. Then you've splitted it on two strings, that are still not JSON. Then you trying to instantiate plot object with data: your_string_value. Here plot waiting of an object, not string.
Try to define data of your plot this way: data:$.parseJSON( dataArray1 )
I can't seem to get my jqplot bar graph to stack. I have the following code:
// Pass/Fail rates per request
$.jqplot('passFailPerRequestStats', [passRate, failRate], {
title: 'Automation Pass Count Per Test Plan',
//stackSeries: true,
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
renderOptions: { barMargin: 25 },
pointLabels: { show: true, stackedValue: true }
},
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer,
tickOptions: {
angle: -30,
fontSize: '10pt'
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
This is successfully displaying a side by side bar graph for both series. However, when I try to stack them by uncommenting out the stackSeries: true, all bar graphs are taken off the graph (and all point labels are displayed on the Y axis labels).
What am I doing wrong?
You need to include barDirection in your rendererOptions object.
rendererOptions: {
barDirection: 'vertical',
highlightMouseDown: true
}
Be sure to include the comma after the last bracket, if more options follow this.
The stack requires the xaxis to be specified also.
Your data structure should look like this. with the leading number in each item indicating the X axis.
var s1 = [[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[11,11],[12,12]];
var s2 = [[1,12],[2,11],[3,10],[4,9],[5,8],[6,7],[7,6],[8,5],[9,4],[10,3],[11,2],[12,1]];
var s3 = [[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[11,11],[12,12]];
var months = ['Jan', 'Feb', 'Mar', 'Apr',"May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
plot4 = $.jqplot('chartdiv', [
s1,
s2,
s3
],
Use the months (or whatever text you want) in the ticks: option like so.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: months
}
I am adding this solution as I found the previously posted one to not work in my environment (although it did put me on the right track, so thanks #Jack) - The following worked for me on an ASP.NET MVC3 site running jqPlot 1.0.8r1250 with JQuery 1.9.1 and JQuery UI 1.1O.3:
For me adding render rendererOptions{...} turned out to be unnecessary.
I also found that stackedValue: true under the seriesDefaults > pointLabels node had no effect, instead I had to uncomment stackSeries: true under the root node.
My final code:
var s1 = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], [10, 10], [11, 11], [12, 12]];
var s2 = [[1, 12], [2, 11], [3, 10], [4, 9], [5, 8], [6, 7], [7, 6], [8, 5], [9, 4], [10, 3], [11, 2], [12, 1]];
var s3 = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], [10, 10], [11, 11], [12, 12]];
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
$.jqplot('chartdiv', [s1, s2, s3], {
title: 'Automation Pass Count Per Test Plan',
stackSeries: true,
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
renderOptions: { barMargin: 25 }
},
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer,
tickOptions: {
angle: -30,
fontSize: '10pt'
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: months
}
}
});
Also make sure you include the following links:
<script src="/.../jquery.jqplot.min.js" type="text/javascript"></script>
<script src="/.../jqplot.barRenderer.min.js" type="text/javascript"></script>
<script src="/.../jqplot.canvasTextRenderer.min.js" type="text/javascript"></script>
<script src="/.../jqplot.dateAxisRenderer.min.js" type="text/javascript"></script>
<script src="/.../jqplot.canvasAxisTickRenderer.min.js" type="text/javascript"></script>
<script src="/.../jqplot.categoryAxisRenderer.min.js" type="text/javascript"></script>
<script src="/.../jqplot.canvasAxisLabelRenderer.min.js" type="text/javascript"></script>
Hope this of help to someone in the future