canvasjs, create a graph with variable data/legend - javascript

I'm trying to create a pie chart in canvasjs, using predetermined data (AKA from the DB).
On the side of Canvasjs, there is a helpful tutoriol to put multiple data in a graph (using a weakly typed array), but I don't know how to do this for the legend. I have tried something, but it doesn't seem to quite work yet.
My code will be posted below, if anyone knows how I could create a legend or something that substitutes it, I'd be very grateful!
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var dps = [{y: 10}, {y: 13}, {y: 18}, {y: 20}];
var bmp = [{x:"Wii U"}, { x: "3DS"}, { x: "PS3"}, { x: "Xbox One"}];
//dataPoints.
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Test title"
},
data: [{
type: "pie",
dataPoints : dps,
indexLabels : bmp
}],
legendText: bmp
});
chart.render();
var xVal = dps.length + 1;
var yVal = 15;
var updateInterval = 1000;
var updateChart = function () {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({x: xVal,y: yVal});
xVal++;
if (dps.length > 10 )
{
dps.shift();
}
chart.render();
// update chart after specified time.
};
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>

You done good job, but you placed Labels to wrong array
var dps = [
{y: 10, legendText:"Wii U", label: "Wii U 10%"},
{y: 13, legendText:"3DS", label: "3DS 13%"},
{y: 18, legendText:"PS3", label: "PS3 18%"},
{y: 20, legendText:"Xbox One", label: "Xbox One 20%"}
];
DEMO
You can find more examples here

Related

3D scatter plot, assign color to a point based on a field

I am trying to color each point on my scatterplot according to the continent it is on. I have my code below but I am unsure as to how I can reference the continent field for each entry, and then assign it to the color field in trace1.
I tried something such as below but no luck.
EDIT:: This has been answered -> Also, how can I pull from the github?
Here is my code below.
<!DOCTYPE html>
<html>
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-2.11.1.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
<body>
<svg id="visualisation" width="1355" height="333"></svg>
<script src="https://cdn.plot.ly/plotly-2.11.1.min.js" charset="utf-8"></script>
<script>
d3.csv('https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/4_ThreeNum.csv', function(err, rows){
function unpack(rows, key) {
return rows.map(function(row)
{ return row[key]; });}
const asia = [];
const condition = unpack(rows, 'continent');
const j = 0;
for(let i = 0; i < condition.length;i++ ){
if(condition[i] === 'asia'){
asia[j] = condition[i];
j++;
}
}
console.log(asia[0]);
var trace1 = {
x:unpack(rows, 'lifeExp'), y: unpack(rows, 'gdpPercap'), z: unpack(rows, 'pop'),
mode: 'markers',
marker: {
size: 12,
line: {
color: 'rgba(217, 217, 217, 0.14)',
width: 0.5},
opacity: 0.8},
type: 'scatter3d'
};
var data = [trace1];
var layout = {
width: 1000,
height: 1000,
margin: {
l: 0,
r: 0,
b: 100,
t: 0
},
scene: {
xaxis: { title: asia[1] },
yaxis: { title: "Population" },
zaxis: { title: "GDP per cap" },
},
};
Plotly.newPlot('myDiv', data, layout);
});
</script>
</body>
</html>

Plotly.js surface plot data formatting

I'm trying to plot a surface plot of a function by generating the points myself via a for loop. The graph however doesn't show up. I've read that the z entry in the data variable for surface plots has to be an array of arrays but even that hasn't made the plot show up.
var zPts = [];
var xPts = [];
var yPts = [];
for(x=0; x<1; x+=0.01) {
for (y=0; y<1; y+=0.01) {
zPts.push([Math.sin(x*y)]);
yPts.push(y);
xPts.push(x);
}
}
var data = [{
z: zPts,
x: xPts,
y: yPts,
type: 'surface'
}];
var layout = {
title: 'My Plot',
autosize: false,
width: 500,
height: 500,
margin: {
l: 65,
r: 50,
b: 65,
t: 90,
}
};
Plotly.newPlot('theDiv', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="theDiv"></div>
After some messing around I've found that the following code produces the plots needed
with only the addition of 3 temporary array variables needed. I believe the correct formatting for the data is that the x, y and z arrays have to all be an array of arrays with each sub array being the same size for all 3.
var zPts = [];
var xPts = [];
var yPts = [];
for(x=0; x<10; x+=0.1) {
let zTemp = [];
let yTemp = [];
let xTemp = [];
for (y=0; y<10; y+=0.1) {
zTemp.push(Math.sin(x)*Math.cos(y));
yTemp.push(y);
xTemp.push(x);
}
zPts.push(zTemp);
yPts.push(yTemp);
xPts.push(xTemp);
}
var data = [{
z: zPts,
x: xPts,
y: yPts,
type: 'surface'
}];
var layout = {
title: 'My Plot',
autosize: false,
width: 500,
height: 500,
margin: {
l: 65,
r: 50,
b: 65,
t: 90,
}
};
Plotly.newPlot('theDiv', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="theDiv"></div>

Is there a way to get the "customdata" property of a clicked point in Plotly?

As far as I understood the documentation of Plotly the clickEvent can only hand over the coordinates of the nearest point to the cursor position. But is there any way to get the clicked point's properties like "text" or in my case the "customdata"?
Edit:
I am not even sure, if I used the customdata property right:
var trace = {
x: [5],
y: [7],
name: 'example',
hovertemplate: '%{text}',
text: ['example'],
mode: 'markers',
visible: 'legendonly',
marker: {
size: [257],
sizeref: 2,
sizemode: 'area',
opacity: 0.3,
customdata: ['https://google.com/']
}
};
customdata needs to be assigned to your trace data, not the marker object.
The plotly_click event returns the points with all its attributes. You can then access customdata and text for each clicked point.
The example below is based on https://plotly.com/javascript/click-events/#binding-to-click-events
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var myPlot = document.getElementById('myDiv'),
d3 = Plotly.d3,
N = 26,
x = d3.range(N),
y = d3.range(N).map( d3.random.normal() ),
customdata = d3.range(N).map(x => characters[x]),
text = d3.range(N).map(x => characters[x] + '-' + characters[x])
data = [ {
x: x,
y: y,
type: 'scatter',
customdata: customdata,
text: text,
mode: 'markers',
marker: {size: 16}
} ],
layout = {
hovermode: 'closest',
title: 'Click on Points',
hovertemplate: '%{text}'
};
Plotly.newPlot('myDiv', data, layout);
myPlot.on('plotly_click', function(data){
var msg = 'Closest point clicked:';
for(var i=0; i < data.points.length; i++){
msg += '\ncustomdata = ' + data.points[i].customdata;
msg += '\ntext = ' + data.points[i].text;
}
alert(msg);
});
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv" style:width: 100%></div>
</body>

Dynamically Toggle Visibility of Shapes in Plotly.js

I am creating an array of plotly.js shapes which work great. I have added a custom data attribute of 'custType' : '1' or 'custType' : '2' based on the type of shape. The number of each shape type will not be consistent so I need to be able to update the visibility dynamically.
I have tried this... to no avail
var update = [];
for(x=0; x<data.layout.shapes.length; x++){
if(data.layout.shapes[x].custType == '1'){
update.push({'shapes[' + x + '].visible':false})
}
}
Plotly.relayout('main', update);
update has to be an object instead of an array, like
{
"shapes[0].visible": false,
"shapes[1].visible": false
}
See the snippet below.
const trace = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: 'scatter'
};
const data = [trace];
const layout = {
shapes: [
{
type: 'rect',
x0: 1,
x1: 2,
y0: 10,
y1: 12,
fillcolor: '#d3d3d3',
line: {
width: 0
}
},
{
type: 'rect',
x0: 3,
x1: 4,
y0: 12,
y1: 14,
fillcolor: '#d3d3d3',
line: {
width: 0
}
}
]
}
Plotly.newPlot('myDiv', data, layout);
function update() {
const update = {};
for(let i = 0; i < layout.shapes.length; i++){
update['shapes[' + i + '].visible'] = false;
}
Plotly.relayout('myDiv', update);
}
<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>
<button type="button" onClick="update()">Update</button>
</body>

How can i get access to a dojox-chart?

How can i get access to a dojox-chart and fetch it as a js-object?
In a normal dijit widget it works with registry.byId("id") but this doesnt work with a dojox-chart.
I've also tried it with dom.byId, but i need it as an object to call functions, not as a dom-node.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="dijit/themes/claro/claro.css">
<script>dojoConfig = {async: true}</script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.0/dojo/dojo.js"></script>
<script>
require(["dojox/charting/Chart", "dojox/charting/axis2d/Default", "dojox/charting/plot2d/Lines", "dojox/charting/plot2d/Grid", "dojox/charting/themes/Claro", "dojo/ready"],
function(Chart, Default, Lines, Grid, theme, ready){
ready(function(){
var chart1 = new Chart("chartId");
chart1.setTheme(theme);
chart1.addPlot("default", {type: Lines});
chart1.addPlot("Grid", {type: "Grid"});
chart1.addAxis("x",{});
chart1.addAxis("y", {vertical: true});
chart1.addSeries("Visits",[
{ x: 1, y: 200 },
{ x: 2, y: 185 },
{ x: 3, y: 100 },
{ x: 4, y: 110 },
{ x: 5, y: 130 },
{ x: 6, y: 70 },
{ x: 7, y: 30 },
{ x: 8, y: 200 }
]);
chart1.render();
});
});
require(["dojo/ready", "dijit/form/Button", "dojo/dom"], function(ready, Button, dom){
ready(function(){
var button = new Button({
label: "Change my label"
}, "buttonId");
});
});
function tryToAccess()
{
require(["dojo/ready", "dijit/registry", "dojo/dom"], function(ready, registry, dom){
ready(function(){
var button = registry.byId("buttonId");
console.log(button); /*returns an object*/
button.set("label","successfully changed!");
/*var chart = ????????????????; */
});
});
}
</script>
</head>
<body class="claro">
<button id="buttonId"></button>
<div id="chartId" style="height: 300px;"></div>
<!-- JUST 4 DEBUGGING -->
<button onClick="tryToAccess();">try to access</button>
</body>
</html>
dojox.charting.Chart is not a widget, try using dojox.charting.widget.Chart instead. I think registry.byId would work with that.
var chart1_widget = new Chart({}, "chartId");
var chart1 = chart1_widget.chart;
chart1.setTheme(theme);
...

Categories

Resources