Show only min, max and median in boxplot - plotly js - javascript

i am just getting started with plotly js. And, I am trying to use boxplot, but it is showing min, max, q1, q3 and median. But, I want to display only min,max and median on hover.
My code:
var y0 = [];
var y1 = [];
for (var i = 0; i < 50; i ++) {
y0[i] = Math.random();
y1[i] = Math.random() + 1;
}
var trace1 = {
y: y0,
type: 'box'
};
var data = [trace1];
Plotly.newPlot('myDiv', data);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
jsfiddle

Related

Errors working with bokeh in javascript model

I'm trying to work with Bokeh JS implementation i.e. trying to use the JS API of bokeh to display glyphs. I followed the instructions provided in bokeh documentation, but the page error's out. For example var plt = Bokeh. Plotting is undefined. What's going wrong?
I have included all the CSS/JS files as indicated in the documentation. Below is the code copied from the documentation - trying to get it working
Can someone with bokehjs experience help?
$(function() {
var plt = Bokeh.Plotting;
console.log(Bokeh.Plotting);
// set up some data
var M = 100;
var xx = [];
var yy = [];
var colors = [];
var radii = [];
for (var y = 0; y <= M; y += 4) {
for (var x = 0; x <= M; x += 4) {
xx.push(x);
yy.push(y);
colors.push(plt.color(50 + 2 * x, 30 + 2 * y, 150));
radii.push(Math.random() * 0.4 + 1.7)
}
}
// create a data source
var source = new Bokeh.ColumnDataSource({
data: {
x: xx,
y: yy,
radius: radii,
colors: colors
}
});
// make the plot and add some tools
var tools = "pan,crosshair,wheel_zoom,box_zoom,reset,save";
var p = plt.figure({
title: "Colorful Scatter",
tools: tools
});
// call the circle glyph method to add some circle glyphs
var circles = p.circle({
field: "x"
}, {
field: "y"
}, {
source: source,
radius: radii,
fill_color: colors,
fill_alpha: 0.6,
line_color: null
});
// add the plot to a document and display it
// var doc = new Bokeh.Document();
// doc.add_root(plt);
// var div = $("#plot");
// cosole.log(div);
// Bokeh.embed.add_document_standalone(doc, div);
plt.show(p);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.4.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.4.min.css">
<div id="plot">
</div>
Turns out, Bokeh has changed the JS APIs since 0.12.1 So the above code works for <=0.12.1 but for more recent releases the JS code breaks. The documentation has not changed though. Hoping the documentation is updated soon
Finally, I was able to get BokehJS 0.12.4 to work. The release notes of 0.12.2 contain a small note that the BokehJS API has been split into its own bundle. So when migrating from pre-0.12.2 to a recent version, it is necessary to add the following javascript
https://cdn.bokeh.org/bokeh/release/bokeh-api-0.12.4.min.js
in addition to the existing bokeh-0.12.4.min.js and bokeh-widgets-0.12.4.min.js. After adding this file to your example it works. Unfortunately, this information didn't make it into the official BokehJS documentation yet.
$(function() {
var plt = Bokeh.Plotting;
// set up some data
var M = 100;
var xx = [];
var yy = [];
var colors = [];
var radii = [];
for (var y = 0; y <= M; y += 4) {
for (var x = 0; x <= M; x += 4) {
xx.push(x);
yy.push(y);
colors.push(plt.color(50 + 2 * x, 30 + 2 * y, 150));
radii.push(Math.random() * 0.4 + 1.7)
}
}
// create a data source
var source = new Bokeh.ColumnDataSource({
data: {
x: xx,
y: yy,
radius: radii,
colors: colors
}
});
// make the plot and add some tools
var tools = "pan,crosshair,wheel_zoom,box_zoom,reset,save";
var p = plt.figure({
title: "Colorful Scatter",
tools: tools
});
// call the circle glyph method to add some circle glyphs
var circles = p.circle({
field: "x"
}, {
field: "y"
}, {
source: source,
radius: radii,
fill_color: colors,
fill_alpha: 0.6,
line_color: null
});
plt.show(p);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-api-0.12.4.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.4.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.4.min.css">
<div id="plot"></div>

Is it possible, to highlight bars in Dimple.js bar chart, based on y-axis value?

I'm just wondering is it possible at all in Dimple.js, to highlight bars based on the y axis value ? I have a bar chart with 3 series - X as a CategoryAxis (RefNum), Y as a MeasureAxis (in K's) and Y2 as a PctAxis (in %). On top of the Bars we draw a line, calculated using javascript (e.g. Pareto chart). So the idea is to change the color of those bars, which are over 80% (of Y2), or maybe grey those out, well some how highlight them. Was digging the Dimple.js API documentation, but nothing there ... Also, I've tried to create a simple IF ELSE statement on
myChart.defaultColors= [
new dimple.color("blue"), ];
but without any luck ... Is it possible at all, as I can't find any documentation or tutorials... Ideally, we would like to have something like this:
Not very familiar with the d3, maybe some solutions available through it ? We using dimple.js 2.1.6 and d3.v3
Any help appreciated, thanks.
Here is full code so far:
<!DOCTYPE html>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://dimplejs.org/dist/dimple.v2.1.6.min.js"></script>
</head>
<div id="chartContainer" style="height: 450px"></div>
<div id="chartContainer2" style="height: 450px"></div>
<script>
var svg = dimple.newSvg("#chartContainer", "100%", "100%");
var data =[
{ "Project":"one","Cost":3586900, "Ref":"AB-46" },
{ "Project":"two","Cost":1509270, "Ref":"AB-47" },
{ "Project":"three","Cost":1409250, "Ref":"AB-48" },
{ "Project":"four","Cost":1305270, "Ref":"AB-49" },
{ "Project":"five","Cost":1109270, "Ref":"AB-50" },
{ "Project":"six","Cost":1009270, "Ref":"AB-51" },
{ "Project":"seven","Cost":909270, "Ref":"AB-52" },
{ "Project":"eight","Cost":809270, "Ref":"AB-53" } ];
/*** get the total Cost ****/
var totalAmount = 0;
for(var i = 0; i < data.length; i++){
data[i].Cost = +data[i].Cost;
totalAmount += data[i].Cost;
if(i > 0){
data[i]['CumulativeAmount'] = data[i].Cost + data[i-1].CumulativeAmount;
}else{
data[i]['CumulativeAmount'] = data[i].Cost;
}
}
// calculate cumulative % from the cumulative amounts & total, round %
for(var i = 0; i < data.length; i++){
data[i]['CumulativePercentage'] = (data[i]['CumulativeAmount'] / totalAmount );
data[i]['CumulativePercentage'] = parseFloat(data[i]['CumulativePercentage'].toFixed(2));
}
var myChart= new dimple.chart(svg, data);
x = myChart.addCategoryAxis("x", "Ref");
//x.addOrderRule("x", "Ref");
y = myChart.addMeasureAxis("y", "Cost");
y2 = myChart.addMeasureAxis("y", "CumulativePercentage");
y2.tickFormat = "%";
y2.overrideMin = 0;
y2.overrideMax = 1;
var y3 = myChart.addPctAxis("y", "CumulativePercentage");
y3.hidden = true;
s = myChart.addSeries(null, dimple.plot.bar, [x, y]);
s2 = myChart.addSeries(null, dimple.plot.line, [x, y2]);
s2.lineWeight = 3;
/***** get the value of the 80% of 'CumulativePercentage' */
s3 = myChart.addSeries(null, dimple.plot.area, [x, y2]);
/**** make it invisible, to use custom d3 line later on *****/
s3.lineWeight = 0;
/****** get the 80% of cumulative percentages ****/
s3.data = [{
"CumulativePercentage": 0.8
}];
myChart.draw(1500);
/***** draw a vertical line at 80% of calculated cumulative percentage line on top of the bars *****/
svg.append("line")
.attr("x1", x._scale(s3.data["CumulativePercentage"]))
.attr("x2", x._scale(s3.data["CumulativePercentage"]))
.attr("y1", myChart._yPixels())
.attr("y2", myChart._yPixels() + myChart._heightPixels())
.style("stroke", "red")
.style("stroke-dasharray", "15")
</script>
</body>
</html>
This is what happen when I add an order rule to the x axis, e.g. x.addOrderRule("Ref", true);
But I need that chart looks like this:
Any thoughts on how to perform this ?! Thanks in advance for your help and effort.
I would add this in with straight d3. Something like:
myChart.svg.selectAll(".dimple-bar").filter(function(d) {
return d.y > 60
}).style("fill", "red");
Where myChart is your dimple chart and d.y > 60 is your criteria (y is the data variable holding your y2 values).
Working example:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<script src="http://dimplejs.org/dist/dimple.v2.2.0.min.js"></script>
</head>
<body>
<div id="chartContainer"></div>
<script type="text/javascript">
var svg = dimple.newSvg("#chartContainer", 590, 400);
var data = [{
x: 'one',
y: 10
}, {
x: 'two',
y: 80
}, {
x: 'three',
y: 70
}, {
x: 'four',
y: 30
}, {
x: 'five',
y: 20
}, {
x: 'six',
y: 6
}];
var myChart = new dimple.chart(svg, data);
myChart.setBounds(60, 30, 510, 305)
var x = myChart.addCategoryAxis("x", "x");
myChart.addMeasureAxis("y", "y");
myChart.addSeries(null, dimple.plot.bar);
myChart.draw();
myChart.svg.selectAll(".dimple-bar").filter(function(d) {
return d.y > 60
}).style("fill", "red");
</script>
</body>
</html>
EDITS
I suspect the problem might be that you don't actually have any data bound to that 2nd axis. So, if you want the bar value with respect to the axis you can do:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<script src="http://dimplejs.org/dist/dimple.v2.2.0.min.js"></script>
</head>
<body>
<div id="chartContainer"></div>
<script type="text/javascript">
var svg = dimple.newSvg("#chartContainer", 590, 400);
var data = [{
x: 'one',
y: 10,
anotherY: 1
}, {
x: 'two',
y: 80,
anotherY: 2
}, {
x: 'three',
y: 70,
anotherY: 3
}, {
x: 'four',
y: 30,
anotherY: 4
}, {
x: 'five',
y: 20,
anotherY: 5
}, {
x: 'six',
y: 6,
anotherY: 6
}];
var myChart = new dimple.chart(svg, data);
myChart.setBounds(60, 30, 510, 305)
var x = myChart.addCategoryAxis("x", "x");
var y = myChart.addMeasureAxis("y", "y");
var anotherY = myChart.addMeasureAxis("y", "anotherY");
myChart.addSeries(null, dimple.plot.bar);
myChart.draw();
console.log(myChart);
myChart.svg.selectAll(".dimple-bar").filter(function(d) {
var val_of_bar_on_other_scale = anotherY._scale.invert(y._scale(d.y));
return val_of_bar_on_other_scale > 2
}).style("fill", "red");
</script>
</body>
</html>

CanvasJS synchronize Panning with Image

I am rendering an Graph with CanvasJS.
It´s generated dynamically.
After I stop the generation (or after an specified time) I generate from that an image.
Now I want to load that image AND take the generation of the Graph. So... I am again generating the same data, but this time with the complete (mostly scaled) picture of the data. - This shall work as an fast Overview.
That´s how I am doing it basiclly: (the dynamic data)
<script type="text/javascript">
window.onload = function ()
{
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
zoomEnabled:true,
title :{
text: "Live Random Data"
},
data: [{
type: "stackedColumn",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 100;
var dataLength = 500; // number of dataPoints visible at any point
var arr = [];
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
arr.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
var d= setInterval(function(){updateChart()}, updateInterval);
$("#test").click(function () {
console.log("baa");
clearInterval(d);
});
$("#show").click(function () {
console.log("baa");
dps=[];
dps.push(arr);
chart.render();
});
}
</script>
http://canvasjs.com/editor/?id=http://canvasjs.com/example/gallery/dynamic/realtime_line/
Now, if I am zooming or panning the "Live Data" or on the Image:
I want an synchronization between those two. If I am zooming or panning on the Image I only want to see an opaque rect and the dynamic data has to be really zoomed.
An sync. Example is here http://jsfiddle.net/canvasjs/m5jgk5sg/, but how do I do that with an Image?
Does anyone of you has an idea or how to make an workaround?

My Canvasjs Chart won't updateInterval?

I have this code I have made out of a composition of my own code and the template code of Canvasjs which uses API of Canvasjs to make the chart.
Everything is good, I debugged it nicely and the chart shows with my database data as a source. My database data reads the data from a textfile which has data from a Arduino-based Pulse Sensor.
This is my code:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
$().ready(function () {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
function updateChart( result ) { // move it here!!!
$.getJSON("arduino_data.php", function( result ){
var dataLength = 40; // number of dataPoints visible at any point
var updateInterval = 20;
var chart = new CanvasJS.Chart("chartContainer",{ // new chart Object
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
if (dataPoints.length > dataLength){
dataPoints.shift();
}
chart.render();
});
}
// First read - Start
updateChart();
// Update chart after specified time.
setInterval(updateChart, updateInterval);
});
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
Why do dataLength = 40; and updateInterval=20 and the last line: updateChart();
do not work? Should there be something in updateChart() like updateChart(dataPoints) ??
Why is my chart not live, though I have the right code parts?
EDIT
This is the template code that works without database data. And this is a Live Chart. It updates every second or so.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer2",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
As you can see, it is just like my code. However this uses math.randomize data instead of real data from database.
My Question: Why won't my chart keep updating (live) so it will show changes? My chart remains static. I have to refresh it manually to show new data transmission.

Toggle Google Chart series within Angular directive

Just starting with Angular. I need to incorporate Google Charts into an Angular app.
Found this plunk (code posted in snippet below), illustrating how to use Google Charts within a directive:
<html xmlns="http://www.w3.org/1999/html">
<head>
<title>
Google Chart Tools AngularJS Directive Example
</title>
</head>
<body ng-app="google-chart-example" ng-controller="MainCtrl">
<h1>Google Chart Tools AngularJS Directive Example</h1>
<p>This is probably the most simple example you can get. It
just shows you what you need to get the Google Chart Tools AngularJS Directive to work.
</p>
<div>
<div google-chart chart="chart" style="{{chart.cssStyle}}"/>
</div>
<p>
Here are the steps:
<ol>
<li>Download ng-google-chart.js from github and add a script tag to your html.</li>
<li>Create a div like: <b><pre ng-non-bindable> <div google-chart chart="chart" style="{{chart.cssStyle}}"/></pre></b></li>
<li>Add 'googlechart' to your module like this: <b><pre>angular.module('myApp',[ 'googlechart', ...</pre></b></li>
<li>Populate the <b>$scope.chart</b> like this:</li>
</ol>
<pre>{{chart | json}}</pre>
</p>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="http://bouil.github.io/angular-google-chart/ng-google-chart.js"></script>
<script src="example.js"></script>
</body>
</html>
One of my requirements is to enable users to toggle visibility of an individual chart series on and off, either by clicking on the corresponding legend, or in some similar way.
I also found this JSFiddle example of toggling visibility on and off outside of Angular:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y1');
data.addColumn('number', 'y2');
data.addColumn('number', 'y3');
// add random data
var y1 = 50, y2 = 50, y3 = 50;
for (var i = 0; i < 100; i++) {
y1 += Math.floor(Math.random() * 5) * Math.pow(-1, Math.floor(Math.random() * 2));
y2 += Math.floor(Math.random() * 5) * Math.pow(-1, Math.floor(Math.random() * 2));
y3 += Math.floor(Math.random() * 5) * Math.pow(-1, Math.floor(Math.random() * 2));
data.addRow([i, y1, y2, y3]);
}
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
// create columns array
var columns = [];
// display these data series by default
var defaultSeries = [1, 3];
var series = {};
for (var i = 0; i < data.getNumberOfColumns(); i++) {
if (i == 0 || defaultSeries.indexOf(i) > -1) {
// if the column is the domain column or in the default list, display the series
columns.push(i);
}
else {
// otherwise, hide it
columns.push({
label: data.getColumnLabel(i),
type: data.getColumnType(i),
sourceColumn: i,
calc: function () {
return null;
}
});
}
if (i > 0) {
columns.push({
calc: 'stringify',
sourceColumn: i,
type: 'string',
role: 'annotation'
});
// set the default series option
series[i - 1] = {};
if (defaultSeries.indexOf(i) == -1) {
// backup the default color (if set)
if (typeof(series[i - 1].color) !== 'undefined') {
series[i - 1].backupColor = series[i - 1].color;
}
series[i - 1].color = '#CCCCCC';
}
}
}
var options = {
width: 600,
height: 400,
series: series
}
function showHideSeries () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row == null) {
var col = sel[0].column;
if (typeof(columns[col]) == 'number') {
var src = columns[col];
// hide the data series
columns[col] = {
label: data.getColumnLabel(src),
type: data.getColumnType(src),
sourceColumn: src,
calc: function () {
return null;
}
};
// grey out the legend entry
series[src - 1].color = '#CCCCCC';
}
else {
var src = columns[col].sourceColumn;
// show the data series
columns[col] = src;
series[src - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
}
google.visualization.events.addListener(chart, 'select', showHideSeries);
// create a view with the default columns
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="chart_div"></div>
<div id="creativeCommons" style="text-align: center; width: 400px;">
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-sa/3.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/InteractiveResource" property="dct:title" rel="dct:type">Code to turn on or off data series by clicking on legend entries</span> by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">Andrew Gallant</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.
</div>
I'm so terribly inexperienced with JavaScript, I do not know how to combine the two, to end up with a directive, which would include this visibility toggle feature.
If anyone knows how this is done, I would really be grateful.

Categories