Related
`
<html>
<head>
<script src="https://cdn.plot.ly/plotly-1.58.5.min.js"></script>
<style>
.graph-container {
display: flex;
justify-content: center;
align-items: center;
}
.main-panel {
width: 70%;
float: left;
}
.side-panel {
width: 30%;
background-color: lightgray;
min-height: 300px;
overflow: auto;
float: right;
}
</style>
</head>
<body>
<div class="graph-container">
<div id="myDiv" class="main-panel"></div>
<div id="lineGraph" class="side-panel"></div>
</div>
<script>
var nodes = [
{ x: 0, y: 0, z: 0, value: [1, 2, 3] },
{ x: 1, y: 1, z: 1, value: [4, 5, 6] },
{ x: 2, y: 0, z: 2, value: [7, 8, 9] },
{ x: 3, y: 1, z: 3, value: [10, 11, 12] },
{ x: 4, y: 0, z: 4, value: [13, 14, 15] }
];
var edges = [
{ source: 0, target: 1 },
{ source: 1, target: 2 },
{ source: 2, target: 3 },
{ source: 3, target: 4 }
];
var x = [];
var y = [];
var z = [];
for (var i = 0; i < nodes.length; i++) {
x.push(nodes[i].x);
y.push(nodes[i].y);
z.push(nodes[i].z);
}
const edge_x = [];
const edge_y = [];
const edge_z = [];
for (var i = 0; i < edges.length; i++) {
const a = nodes[edges[i].source];
const b = nodes[edges[i].target];
edge_x.push(a.x, b.x, null);
edge_y.push(a.y, b.y, null);
edge_z.push(a.z, b.z, null);
}
var traceNodes = {
x: x, y: y, z: z,
mode: 'markers',
// marker: { size: 12, color: 'red' },
// marker: { size: 12, color: Array.from({length: nodes.length}, () => 'red') },
text: [0, 1, 2, 3, 4],
// add the color gradient to the nodes from red to blue
// marker: { size: 12, color: Array.from({length: nodes.length}, () => 'red'), colorscale: 'Viridis'},
marker:{color: [1,2,3,4,5],colorscale: [[0, 'rgb(255, 0, 0)'], [1, 'rgb(0, 0, 255)']], showscale: true, size: 12},
hoverinfo: 'text',
hoverlabel: {
bgcolor: 'white'
},
customdata: nodes.map(function(node) {
if (node.value !== undefined)
return node.value;
}),
type: 'scatter3d'
};
var traceEdges = {
x: edge_x,
y: edge_y,
z: edge_z,
//add the color gradient to the lines from red to blue
// line: { color: Array.from({length: edge_x.length}, () => 'red'), width: 5, colorscale: 'Viridis'},
line: {
color: [4,1,4,1,4,1],
colorscale: [[0, 'rgb(255, 0, 0)'], [1, 'rgb(0, 0, 255)']],
showscale: true,
width: 5
},
type: 'scatter3d',
mode: 'lines',
// line: { color: 'red', width: 2, arrow: {size: 50, color: 'black', end:1}},
// line: { color: 'red', width: 2, shape: 'spline', arrow: {size: 500, color: 'black', end:1}},
//add color gradient to the lines
// line: { width: 2, shape: 'spline', arrow: {size: 500, color: 'black', end:1}, colorscale: 'Viridis'},
opacity: 2.8
//add cones shape to the end of the lines
};
var layout = {
margin: { l: 0, r: 0, b: 0, t: 0 }
};
// var traceCone = {
// type: "cone",
// x: [1], y: [1], z: [1],
// u: [1], v: [1], w: [0]
// };
//add the cones shape at the middle of the lines and they are pointing to the end of the lines
var traceCone = {
type: "cone",
x: [0.5, 1.5, 2.5, 3.5], y: [0.5, 0.5, 0.5, 0.5], z: [0.5, 1.5, 2.5, 3.5],
u: [1,1,1,1], v: [1,-1,1,-1], w: [1,1,1,1],
//set the size of the cones
sizemode: "absolute",
sizeref: 0.5,
// give color to cone which have co-oridnates (0.5,0.5,0.5)
colorscale: [[0, 'rgb(255, 0, 0)'], [1, 'rgb(0, 0, 255)']],
// color: [1,2,3,4], // color array
// colorscale: 'Viridis',
showscale: false
// colorscale: 'Viridis',
// color: [1,4,1,1,4,1],
// showscale: false,
};
Plotly.newPlot('myDiv', [traceNodes, traceEdges,traceCone],layout, { displayModeBar: false });
// max y value for the line plot
const ymax = Math.max(...nodes.map(n => n.value).flat());
document.getElementById('myDiv').on('plotly_click', function(data){
var nodeIndex = data.points[0].pointNumber;
var values = nodes[nodeIndex].value;
//change the color of the clicked node to blue and when clicked on another node, change the color of the previous node to red
var update = {
//give the color of the nodes to the initial color
// marker: { color: Array.from({length: nodes.length}, () => 'red') }
//give the color of the nodes to the color gradient
marker: { color: [1,2,3,4,5],colorscale: [[0, 'rgb(255, 0, 0)'], [1, 'rgb(0, 0, 255)']], showscale: true, size: 12}
};
update.marker.color[nodeIndex] = 'blue';
setTimeout(function() {
Plotly.restyle('myDiv', update);
}, 50);
Plotly.newPlot('lineGraph', [{
type: 'scatter',
mode: 'lines',
x: [0, 1, 2],
y: values
}], {
margin: { t: 0 },
yaxis: {autorange: false, range: [0, ymax + 1]}
});
});
</script>
</body>
</html>
The code above shows how to display a 3D network graph , and cones were used as an arrow of the edge.Basically we wanted to give different colors to the cones,but its not working...
Please help us to way out of this problem.
So,the code that I have shown ,assign same color to all the cones (which I dont want), is there any way out?
Unlike scatter traces, cone traces don't have a color property where you can specify an array of numbers that are mapped to a color scale. You can only define what the colorscale is, and its bounds in the color space using cmin and cmax.
The thing (number) that determines the color of a cone is its u/v/w norm in the vector field, and it seems that it's not possible to decide arbitrarily - regardless of that norm - how each cone should be colored.
If I'm not wrong the u/v/w norm is computed as follows :
const norm = Math.sqrt(u**2 + v**2 + w**2);
In your example, all cones are assigned the same color because they all have the same norm, which is √3. If you try to assign different u/v/w values, it should change accordingly.
I have a simple json file:
{
"id": 1,
"name": "Bitcoin",
"quantity": 1,
"price": 1,
"old_price": 0.99,
"info": "The most famous one",
"archived_data": [
{
"id": 0,
"name": "jan",
"sold": 5,
"bought": 3
},
{
"id": 1,
"name": "feb",
"sold": 15,
"bought": 30
},
{
"id": 2,
"name": "mar",
"sold": 5,
"bought": 3
},
{
"id": 3,
"name": "apr",
"sold": 15,
"bought": 30
}
]
}
I now want to display them in my chart:
import CanvasJSReact from '../plugins/canvasjs.react';
import React, {Component} from 'react';
const CanvasJSChart = CanvasJSReact.CanvasJSChart;
class CryptoChart extends Component {
constructor(props) {
super(props);
this.toggleDataSeries = this.toggleDataSeries.bind(this);
}
toggleDataSeries(e){
e.dataSeries.visible = !(typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible);
this.chart.render();
}
render() {
const options = {
theme: "light2",
animationEnabled: true,
axisX: {
title: "Months"
},
axisY: {
title: "Sold",
titleFontColor: "#007bff",
lineColor: "#007bff",
labelFontColor: "#007bff",
tickColor: "#007bff"
},
axisY2: {
title: "Bought",
titleFontColor: "#51CDA0",
lineColor: "#51CDA0",
labelFontColor: "#51CDA0",
tickColor: "#51CDA0"
},
toolTip: {
shared: true
},
legend: {
cursor: "pointer",
itemclick: this.toggleDataSeries
},
data: [
{
type: "spline",
name: "Sold",
showInLegend: true,
xValueFormatString: "MMM YYYY",
yValueFormatString: "#,##0 Units",
dataPoints: [
{ x: new Date(2020, 0, 1), y: this.props.crypto.archived_data[0].sold },
{ x: new Date(2020, 1, 1), y: this.props.crypto.archived_data[1].sold },
{ x: new Date(2020, 2, 1), y: this.props.crypto.archived_data[2].sold },
{ x: new Date(2020, 3, 1), y: this.props.crypto.archived_data[3].sold },
{ x: new Date(2020, 4, 1), y: this.props.crypto.archived_data[4].sold },
{ x: new Date(2020, 5, 1), y: this.props.crypto.archived_data[5].sold },
{ x: new Date(2020, 6, 1), y: this.props.crypto.archived_data[6].sold },
{ x: new Date(2020, 7, 1), y: this.props.crypto.archived_data[7].sold },
{ x: new Date(2020, 8, 1), y: this.props.crypto.archived_data[8].sold },
{ x: new Date(2020, 9, 1), y: this.props.crypto.archived_data[9].sold },
{ x: new Date(2020, 10, 1), y: this.props.crypto.archived_data[10].sold },
{ x: new Date(2020, 11, 1), y: this.props.crypto.quantity}
]
},
{
type: "spline",
name: "Bought",
axisYType: "secondary",
showInLegend: true,
xValueFormatString: "MMM YYYY",
yValueFormatString: "$#,##0.#",
dataPoints: [
{ x: new Date(2020, 0, 1), y: this.props.crypto.archived_data[0].bought },
{ x: new Date(2020, 1, 1), y: this.props.crypto.archived_data[1].bought },
{ x: new Date(2020, 2, 1), y: this.props.crypto.archived_data[2].bought },
{ x: new Date(2020, 3, 1), y: this.props.crypto.archived_data[3].bought },
{ x: new Date(2020, 4, 1), y: this.props.crypto.archived_data[4].bought },
{ x: new Date(2020, 5, 1), y: this.props.crypto.archived_data[5].bought },
{ x: new Date(2020, 6, 1), y: this.props.crypto.archived_data[6].bought },
{ x: new Date(2020, 7, 1), y: this.props.crypto.archived_data[7].bought },
{ x: new Date(2020, 8, 1), y: this.props.crypto.archived_data[8].bought },
{ x: new Date(2020, 9, 1), y: this.props.crypto.archived_data[9].bought },
{ x: new Date(2020, 10, 1), y: this.props.crypto.archived_data[10].bought },
{ x: new Date(2020, 11, 1), y: this.props.crypto.quantity }
]
}
]
}
return (
<div>
<CanvasJSChart options = {options} onRef={ref => this.chart = ref} />
</div>
);
}
} export default CryptoChart;
The this.props.crypto.quantity works as expected, but the this.props.crypto.archived_data[0].sold and this.props.crypto.archived_data[0].bought don't work: the app crashes and the console says
TypeError: Cannot read property '0' of undefined
Does anyone know how to output this?
Edit: Ive made a react.new here so its easier to see what is going wrong and maybe how it can be fixed
I am new to using highcharts.js. I want to create an activity gauge chart using data from a json file or url. I have understood how they draw the chart but failed to understand the data format used in json to display the chart.
Here is my code
var options = {
chart: {
type: 'solidgauge',
marginTop: 50
},
title: {
text: 'Activity',
style: {
fontSize: '24px'
}
},
tooltip: {
borderWidth: 0,
backgroundColor: 'none',
shadow: false,
style: {
fontSize: '16px'
},
pointFormat: '{series.name}<br><span style="font-size:2em; color: {point.color}; font-weight: bold">{point.y}%</span>',
positioner: function (labelWidth, labelHeight) {
return {
x: 200 - labelWidth / 2,
y: 180
};
}
},
pane: {
startAngle: 0,
endAngle: 360,
background: [{ // Track for Move
outerRadius: '112%',
innerRadius: '88%',
backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0.3).get(),
borderWidth: 0
}, { // Track for Exercise
outerRadius: '87%',
innerRadius: '63%',
backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[1]).setOpacity(0.3).get(),
borderWidth: 0
}, { // Track for Stand
outerRadius: '62%',
innerRadius: '38%',
backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[2]).setOpacity(0.3).get(),
borderWidth: 0
}]
},
yAxis: {
min: 0,
max: 100,
lineWidth: 0,
tickPositions: []
},
plotOptions: {
solidgauge: {
borderWidth: '34px',
dataLabels: {
enabled: false
},
linecap: 'round',
stickyTracking: false
}
},
series: []
};
var gauge1;
$.getJSON('bryan.json', function(json){
console.log(json)
options.chart.renderTo = 'container';
options.series.data = json
gauge1 = new Highcharts.Chart(options);
});
/**
* In the chart load callback, add icons on top of the circular shapes
*/
function callback()
{
// Move icon
this.renderer.path(['M', -8, 0, 'L', 8, 0, 'M', 0, -8, 'L', 8, 0, 0, 8])
.attr({
'stroke': '#ffffff',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'stroke-width': 2,
'zIndex': 10
})
.translate(190, 26)
.add(this.series[2].group);
// Exercise icon
this.renderer.path(['M', -8, 0, 'L', 8, 0, 'M', 0, -8, 'L', 8, 0, 0, 8, 'M', 8, -8, 'L', 16, 0, 8, 8])
.attr({
'stroke': '#ffffff',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'stroke-width': 2,
'zIndex': 10
})
.translate(190, 61)
.add(this.series[2].group);
// Stand icon
this.renderer.path(['M', 0, 8, 'L', 0, -8, 'M', -8, 0, 'L', 0, -8, 8, 0])
.attr({
'stroke': '#ffffff',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'stroke-width': 2,
'zIndex': 10
})
.translate(190, 96)
.add(this.series[2].group);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" style="width: 400px; height: 400px; margin: 0 auto">
</div>
And here is my json data which i thout might be rendered but it didnot.
data.json
First of all, instead of options.series.data = json, you need to create the first series and then populate its data array with your data. Also, set in each point different radius and innerRadius properties. Take a look at the example below.
API Reference:
http://api.highcharts.com/highcharts/series.solidgauge.data.radius
http://api.highcharts.com/highcharts/series.solidgauge.data.innerRadius
Example:
http://jsfiddle.net/x3cne1ng/
I had finished my site using highcharts, but as it only could happen... I need to switch to Highstock.
Unfortunately I've got problems to change the code although it's mostly the same... I had 3 line series and now want to switch it to one candlestick and two spline area series.
php file looks like this and the output seems to be fine:
<?php
session_start();
?>
<?php
define('DB_SERVER',"");
define('DB_NAME',"");
define('DB_USER',"");
define('DB_PASSWORD',"");
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $con);
if (isset($_GET["dateParam"])) {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts, OpenBid AS open, HighBid AS high, LowBid AS low, CloseBid AS close FROM ger30 WHERE datetime LIKE '".$_GET["dateParam"]."%' ORDER BY datetime");
} else {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts, OpenBid AS open, HighBid AS high, LowBid AS low, CloseBid AS close FROM ger30 WHERE DATE(datetime) = CURDATE() ORDER BY datetime");
}
while ($row = mysql_fetch_assoc($sql)) {
if ($row['ts'] == ""){
$row['ts'] = "0";
}
if ($row['open'] == ""){
$row['open'] = 0;
}
if ($row['high'] == ""){
$row['high'] = 0;
}
if ($row['low'] == ""){
$row['low'] = 0;
}
if ($row['close'] == ""){
$row['close'] = 0;
}
$t = $row['ts'];
$o = $row['open'];
$h = $row['high'];
$l = $row['low'];
$c = $row['close'];
$result['data1'][] = array( $t, $o, $h, $l, $c );
}
if (isset($_GET["dateParam"])) {
$sql = mysql_query("SELECT reference FROM kalender WHERE date LIKE '".$_GET["dateParam"]."%'");
} else {
$sql = mysql_query("SELECT reference FROM kalender WHERE DATE(date) = CURDATE()");
}
while ($row = mysql_fetch_assoc($sql)) {
$ref1 = $row['reference'];
}
if (isset($_GET["dateParam"])) {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts2, HighBid AS high2, LowBid AS low2 FROM ger30 WHERE DATE(datetime) LIKE DATE('$ref1') ORDER BY datetime");
} else {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts2, HighBid AS high2, LowBid AS low2 FROM ger30 WHERE DATE(datetime) = CURDATE() ORDER BY datetime");
}
while ($row = mysql_fetch_assoc($sql)) {
if ($row['ts2'] == ""){
$row['ts2'] = "0";
}
if ($row['high2'] == ""){
$row['high2'] = 0;
}
if ($row['low2'] == ""){
$row['low2'] = 0;
}
$t2 = $row['ts2'];
$h2 = $row['high2'];
$l2 = $row['low2'];
$result['data2'][] = array( $t2, $h2, $l2 );
$result['data3'][] = array( $t2, $h2, $l2 );
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
so far I recieve 3 correct arrays looking like this:
data1: [1389250800000,9484,9484,9480,9483],[1389250860000,9483,9484,9480,9482]...
data2: [1389078120000,9444,9441],[1389078180000,9444,9442]...
data3: [1389078120000,9444,9441],[1389078180000,9444,9442]
and my java code looks like this:
var options;
$(document).ready(function() {
$.getJSON("testdata2.php", function(json){
options.series[0].data = json['data1'];
chart = new Highcharts.Chart(options);
});
// create the chart
$('#container').highcharts('StockChart', {
options = {
chart:
{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, 'rgb(51, 51, 51)'],
[1, 'rgb(16, 16, 16)']
]
},
borderColor: '#666666',
borderWidth: 1,
borderRadius: 0,
zoomType: 'x',
maxZoom: 60000,
renderTo: 'container'
},
rangeSelector : {
enabled: false
},
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, 'rgb(51, 51, 51)'],
[1, 'rgb(16, 16, 16)']
]
},
xAxis: {
type: 'datetime',
lineColor: '#666666',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: { // first yAxis
alternateGridColor: null,
minorTickInterval: null,
gridLineColor: 'rgba(255, 255, 255, .1)',
minorGridLineColor: 'rgba(255,255,255,0.07)',
lineWidth: 0,
tickWidth: 0,
labels: {
style: {
color: '#999',
fontWeight: 'bold'
}
},
title: {
text: 'DAX',
style: {
color: '#eeeeee'
}
}
},
tooltip: {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, 'rgba(96, 96, 96, .8)'],
[1, 'rgba(16, 16, 16, .8)']
]
},
borderWidth: 0,
style: {
color: '#FFF'
}
},
title: {
text: 'GER30 Tageschart',
margin: 50,
style: {
fontFamily: 'Verdana',
fontSize: '20px',
fontWeight: 'bold',
color: '#cccccc'
}
},
navigator: {
enabled: false
},
scrollbar: {
enabled: false
},
plotOptions: {
series: {
shadow: true
},
line: {
dataLabels: {
color: '#CCC'
},
marker: {
lineColor: '#333'
}
},
spline: {
marker: {
lineColor: '#333'
}
},
scatter: {
marker: {
lineColor: '#333'
}
},
candlestick: {
lineColor: '#666666'
}
},
series : [{
type : 'candlestick',
name : 'GER30',
data : [],
}]
}
});
});
});
Javascript is updated, to show how it looks like at the moment.
I try to get only one series data work so that I only need to add the others.
The Problem must be somewhere here:
$.getJSON("testdata2.php", function(json){
options.series[0].data = json['data1'];
chart = new Highcharts.Chart(options);
});
If I use
$.getJSON('testdata2.php', function(test) {
instead, and "data: test," in the series part, it works fine.
I am trying to read the data from csv and display it as a input to Speedometer but I am unable to get the chart. Please tell me where i am going wrong.
My code is:
$(document).ready(function() {
var options = {
chart: {
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Speedometer'
},
pane: {
startAngle: -150,
endAngle: 150,
background: [{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#FFF'],
[1, '#333']
]
},
borderWidth: 0,
outerRadius: '109%'
}, {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#333'],
[1, '#FFF']
]
},
borderWidth: 1,
outerRadius: '107%'
}, {
// default background
}, {
backgroundColor: '#DDD',
borderWidth: 0,
outerRadius: '105%',
innerRadius: '103%'
}]
},
// the value axis
yAxis: {
min: 0,
max: 100,
minorTickInterval: 'auto',
minorTickWidth: 1,
minorTickLength: 10,
minorTickPosition: 'inside',
minorTickColor: '#666',
tickPixelInterval: 30,
tickWidth: 2,
tickPosition: 'inside',
tickLength: 10,
tickColor: '#666',
labels: {
step: 2,
rotation: 'auto'
},
title: {
text: 'km/h'
},
plotBands: [{
from: 0,
to: 120,
color: '#55BF3B' // green
}, {
from: 120,
to: 160,
color: '#DDDF0D' // yellow
}, {
from: 160,
to: 200,
color: '#DF5353' // red
}]
},
series: []
};
$.get('data.csv', function(data) {
var series = {
data: [],
name: 'Speed',
tooltip: {
valueSuffix: ' km/h'
}
};
series.data.push(parseFloat(data));
options.series.push(series);
alert("data "+options.series);
var chart = new Highcharts.Chart(options);
});
});
and the csv file is simple
data.csv has only one value 30.
or incase it is
t1,30
t2,40
t3,60
how do i display 3 corresponding speedometers with respective speed.
Your help is greatly appreciated.
Thanks in advance.
In your case data your data (from ajax) is a single string, but you need to split elements and then choose which should be parsed to integer (parseFloat).