ChartJS Linechart weird line at the xAxes - javascript

I'm writing a frontend with Angular 9 that demonstrating exchange rates ratio dynamically. And I'm using a line chart. Line chart's and auto-refreshing is working totally fine. But my chart has a weird bug. I couldn't find any problem looks like mine. I'll write my chart options and screenshots of the weird line.
chart's picture
The gap between the 2 data occurred because the server was closed.
Updated Picture
I figured out that this weird line showing when I gave the xAxes' type as 'time'. I hope you understand my problem.
Chart's options:
lineChartOptions = {
animation: {
duration: 0,
},
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: false,
},
legend: {
labels: {
fontColor: 'white',
fontSize: 18,
fontFamily: 'Sawarabi Mincho',
},
},
scales: {
xAxes: [
{
type: 'time',
ticks: {
autoSkip: false,
maxTicksLimit: 7,
source: 'auto',
beginAtZero: true,
},
time: {
parser: 'HH',
unit: 'minute',
},
displayFormats: {
hour: 'h:mm a',
},
distribution: 'linear',
},
],
},
};
Also, this is the function that I'm sending data of chart Label
//Defining variables
chartData: any = [];
sells: Array<number> = [];
dates: Array<any> = [];
sendDatasToChart() {
this.currencyService
.getMyData()
.subscribe((data) => (this.chartData = data));
for (let i of this.chartData) {
this.sells.push(i['sell']);
const date = new Date(i['date']);
const momentDate = moment(date.toISOString());
this.dates.push(momentDate);
}
this.lineChartData = [
{
data: this.sells,
label: 'USD/TRY Currency Chart',
pointRadius: 0,
},
];
this.lineChartLabels = this.dates;
this.sells = [];
this.dates = [];
this.chartData = [];
}
This is a little part of the API's response that I'm sending to chart:
{
"success": true,
"data": [
{
"_id": "5eea3c070a60764b08475e88",
"dollar": {
"buy": "6,8526",
"sell": "6,8567",
"update": "18:45"
},
"euro": {
"buy": "7,6832",
"sell": "7,6911",
"update": "18:45"
},
"gbp": {
"buy": "8,5824",
"sell": "8,5917",
"update": "18:45"
},
"createdAt": "2020-06-17T15:51:35.226Z",
"__v": 0
},
{
"_id": "5eea3f8b0a60764b08475e89",
"dollar": {
"buy": "6,8528",
"sell": "6,8570",
"update": "19:00"
},
"euro": {
"buy": "7,6898",
"sell": "7,6957",
"update": "19:00"
},
"gbp": {
"buy": "8,5833",
"sell": "8,5900",
"update": "19:00"
},
"createdAt": "2020-06-17T16:06:35.275Z",
"__v": 0
}
}
Also, this is the Angular service that I'm receiving data:
updateChart(){
return this.http
.get(this.path + "/chart-data").subscribe(
(response) => {
for (let i of response['data']) {
this.chartData.push({
sell: Number(i['dollar']['sell'].replace(/,/, '.')),
date: i['createdAt']
})
}
this.myData.next(this.chartData)}
)
}

Related

apache echart not working with pie drill down

the drill down for pie isnt working that well, can you please let me know what im missing?
i want to have a drill down bar chart however, i changed it to pie as its what i need but running into some issues - wondering if someone has done this before, and/ can help find issues with my code.
this is what it looks like right now, cant add legend or get rid of those x axis.
functionality is there but just want to make it work.
json.
{
"highLevelNumbers": [
1269,15,54624,827,42,20895,4856
],
"highLevel":
["Electrical Equipment",
"Enclosures",
"Instrument Equipment",
"Mechanical Equipment",
"Miscellaneous Equipment",
"Piping and Pipeline Equipment",
"Valve"],
"ElectricalEquipment":
[["earthing resistor",52],
["electric battery", 66],
["electric generator", 1],
["electrical control panel", 305],
["electrical isolator", 38],
["electrical switch", 43],
["electronic flow controller", 341],
["electronic level controller", 225],
["electronic pressure controller", 232],
["electronic temperature controller", 121]],
"Enclosures":
[["electrical control panel", 305],
["electrical isolator", 38],
["electrical switch", 43]],
"InstrumentEquipment":
[["electrical isolator", 38],
["electrical switch", 43],
["electronic flow controller", 341]],
"MechanicalEquipment":
[["earthing resistor",52],
["electrical control panel", 305]],
"MiscellaneousEquipment":
[["earthing resistor",52],
["electronic flow controller", 341]],
"PipingandPipelineEquipment":
[["earthing resistor",52],
["electronic flow controller", 341]],
"Valve":
[["earthing resistor",52],
["electrical switch", 43],
["electronic flow controller", 341]]
}
javascript:
function drilldownbar_Graph() {
//values from data_import
//fetch function
fetch("drilldown.json")
.then(function (u) {
return u.json();
})
.then(function (json) {
sketchingDrillDownGraph(json);
//calling and passing json to another function data_function
});
//start of function
function sketchingDrillDownGraph(data) {
//graph
var chartDom = document.getElementById("main6");
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: "Drill Down Category",
left: "center",
borderColor: "#796b94",
borderWidth: 0.1,
},
legend: {
show: true,
},
label: {
show: true,
},
toolbox: {
show: true,
feature: {
mark: { show: true },
restore: { show: true },
saveAsImage: { show: true },
},
},
xAxis: {
data: data.highLevel,
splitLine: {
show: false,
},
},
yAxis: {
splitLine: {
show: false,
},
},
dataGroupId: "",
animationDurationUpdate: 500,
series: {
type: "pie",
radius: ["35%", "65%"],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 9,
borderColor: "black",
borderWidth: 0.5,
},
id: "jafurah",
data: [
{
value: 5,
groupId: "electricalEquipment",
},
{
value: 2,
groupId: "Enclosures",
},
{
value: 4,
groupId: "InstrumentEquipment",
},
{
value: 4,
groupId: "MechanicalEquipment",
},
{
value: 4,
groupId: "MiscellaneousEquipment",
},
{
value: 4,
groupId: "PipingandPipelineEquipment",
},
{
value: 5,
groupId: "Valve",
},
],
universalTransition: {
enabled: true,
divideShape: "clone",
},
},
};
const drilldownData = [
{
dataGroupId: "electricalEquipment",
data: data.electricalEquipment,
},
{
dataGroupId: "Enclosures",
data: data.Enclosures,
},
{
dataGroupId: "InstrumentEquipment",
data: data.InstrumentEquipment,
},
{
dataGroupId: "MechanicalEquipment",
data: data.MechanicalEquipment,
},
{
dataGroupId: "MiscellaneousEquipment",
data: data.MiscellaneousEquipment,
},
{
dataGroupId: "PipingandPipelineEquipment",
data: data.PipingandPipelineEquipment,
},
{
dataGroupId: "Valve",
data: data.Valve,
},
];
myChart.on("click", function (event) {
if (event.data) {
var subData = drilldownData.find(function (data) {
return data.dataGroupId === event.data.groupId;
});
if (!subData) {
return;
}
myChart.setOption({
xAxis: {
data: subData.data.map(function (item) {
return item[0];
}),
},
series: {
type: "pie",
id: "jafurah",
dataGroupId: subData.dataGroupId,
data: subData.data.map(function (item) {
return item[1];
}),
universalTransition: {
enabled: true,
divideShape: "clone",
},
},
graphic: [
{
type: "text",
left: 50,
top: 20,
style: {
text: "Back",
fontSize: 18,
},
onclick: function () {
myChart.setOption(option);
},
},
],
});
}
});
option && myChart.setOption(option);
// getting the data [docs total by day]
}
}
To get rid of xAxis : just remove it in the chart options. (Both xAxis and yAxis actually, no need of that in a pie chart)
To display the legend, you have to set a name to each series.
series : {
data: [
{
value: 5,
groupId: "electricalEquipment",
name: "electricalEquipment", // add this line to each series data
},
...
]
}
Here is the full working code (note that I hardcoded the values instead of using your json file to make it easier for me).
I added a param (notMerge=true) in this method : myChart.setOption(option, true); (in the click event function) so that the "Back" button disappears when it cannot be used.

Kendo Grid Pager Shows No Items To Display

I have defined a Kendo grid as follows:
$(document).ready(function() {
$("#catalogGrid2").kendoGrid(catalogGridOptions);
});
let catalogGridOptions = {
pageable: true,
dataSource: {
serverPaging: true,
//serverGrouping: true,
transport: {
read: {
url: "/gliese/read",
type: "GET",
contentType: "application/json"
}
},
//pageSize: 25,
schema: {
data: "data",
total: "total",
// total: function(response) {
// return response.total;
// },
model: {
id: "catalogID",
fields: {
id: {type: "number"},
name: {type: "string"},
component: {type: "string"}
}
}
},
},
pageable: {
pageSize: 25,
//pageSizes: true,
//pageSizes: [10,25,50,100,"all"],
//input: true,
numeric: true,
refresh: true
},
columns: [
{
field: "id",
hidden: true
},
{
field: "name",
title: "Name",
width: 150
},
{
field: "component",
title: "Component",
width: 75
}
],
};
The data displays correctly in the grid, but there are no pages to navigate through, and the message "No items to display" is in the pager bar as well.
Below is an example of the results being returned:
{
"total": 3803,
"pageSize": 25,
"data": [
{
"id": 12409,
"name": "Sun",
"component": "",
"ra": "00 02 33.8",
"dec": "+00 16 42",
"properMotion": null,
"properMotionDir": null,
"radialVelocity": null,
"spectralTypeFull": "G2 V",
"spectralType": "G",
"spectralTypeSub": "2",
"luminosityClass": "V",
"visualMagnitude": -26.72,
"absoluteMagnitude": 4.85,
"parallax": null,
"bvColor": 0.65,
"hd": null
},
// 24 more results
]
}
Does anyone see any obvious reasons why the pager bar does not work?
EDIT: Added screenshot per request, updated code to newest attempt.

Legend in network graph ( Highchart Js)

I want to show the user about which nodes are some sort of type in network graph of Highchart JS.
For example, the red node would be about "car" and the black node would be about "person".
How can I implement such a legend in Highchart Js?
Here is my codepen.
Highcharts.seriesTypes.networkgraph.prototype.drawLegendSymbol = Highcharts.LegendSymbolMixin.drawRectangle;
Highcharts.chart('container', {
chart: {
type: 'networkgraph'
},
plotOptions: {
networkgraph: {
keys: ['from', 'to']
}
},
legend: {
enabled: true
},
series: [{
showInLegend: true,
data: [
['A', 'B'],
['C','D'],
['E','F']
],
nodes:[{
id:'A',
color:'#ff1000'
},{
id:'B',
color:'#222222'
},
{
id:'C',
color:'#ff1000'
},
{
id:'D',
color:'#222222'
},
{
id:'E',
color:'#ff1000'
},
{
id:'F',
color:'#222222'
},]
}]
});
Thank you in advance.
Have you tried adding the dataLabel to series property and add a name to your nodes.
{
id: "A",
color: "#ff1000",
name: "car" <--------- name property
},
Something like this:
series: {
dataLabels: {
linkFormat: '',
enabled: true,
format: "{point.name}",
crop: false,
defer: false,
useHtml: true,
},
}
Full example:
https://codepen.io/tiagotedsky/pen/zYZYOLR

Apex charts, setting series data from array in state

In my react app, I'm getting results from pouchDB that I want to use as the data points in my series for apexCharts.
I'm getting the results and putting them in state, called maxCalories, and when logging in the console they are in this format:
So I want those 7 numbers (all with the index name of caloriesBurned to be my data in the series for the chart but I'm currently getting NaN on the graph.
Here's the full code, how can I set these to the correct format to use them in the chart data?
import React, { Component } from "react";
import Chart from "react-apexcharts";
import DB from '../../db';
import * as moment from 'moment';
class TrendsComponent extends Component {
constructor(props) {
super(props);
this.state = {
maxCalories: '',
calorieRecord: {
caloriesConsumed: '',
caloriesBurned: '',
createdAt: this.newestDate,
updatedAt: undefined
},
caloriesDB: new DB('calorie-records'),
calories: {},
calorieElements: null,
options: {
},
chart: {
toolbar: {
show:false
},
id: "basic-bar"
},
xaxis: {
categories: ['3/20', '3/21', '3/22', '3/23', '3/24', '3/25','3/26']
}
},
series: [
{
name: "Trend (tracked)",
data: {this.maxCalories}
}
]
};
}
componentDidMount(){
this.setMax();
}
setMax = () => {
this.state.caloriesDB.db.find({
selector: {
$and: [
{_id: {"$gte": null}},
{caloriesBurned: {$exists: true}},
{createdAt: {$exists: true}}
]
},
fields: ['caloriesBurned', 'createdAt'],
sort: [{'_id':'desc'}],
limit: 7
}).then(result => {
console.log('max');
console.log(result);
const newDocs = result.docs;
this.setState({
maxCalories: newDocs.map(docs => docs)
});
console.log('maxCalories');
console.log(this.state.maxCalories);
}).catch((err) =>{
console.log(err);
});
}
render() {
return (
<div className="mixed-chart">
<Chart
options={this.state.options}
series={this.state.series}
type="area"
stacked="true"
width="700"
/>
</div>
);
}
}
export default TrendsComponent;
I had the same problem in my project. And I spent a lot of time in looking for solution. So here what I get:
const FinacialResultChart = (props) => {
const options = {
chart: {
toolbar: {
show: false
},
animations: {
enabled: false
}
},
stroke: {
curve: "smooth",
dashArray: [0, 8],
width: [4, 2]
},
grid: {
borderColor: props.labelColor
},
legend: {
show: false
},
colors: [props.dangerLight, props.strokeColor],
fill: {
type: "gradient",
gradient: {
shade: "dark",
inverseColors: false,
gradientToColors: [props.primary, props.strokeColor],
shadeIntensity: 1,
type: "horizontal",
opacityFrom: 1,
opacityTo: 1,
stops: [0, 100, 100, 100]
}
},
markers: {
size: 0,
hover: {
size: 5
}
},
xaxis: {
labels: {
style: {
colors: props.strokeColor
}
},
axisTicks: {
show: false
},
categories: [
"Январь",
"Февраль",
"Март",
"Апрель",
"Май",
"Июнь",
"Июль",
"Август",
"Сентябрь",
"Октябрь",
"Ноябрь",
"Декабрь"
],
axisBorder: {
show: false
},
tickPlacement: "on"
},
yaxis: {
tickAmount: 5,
labels: {
style: {
color: props.strokeColor
}
}
},
tooltip: {
x: { show: false }
}
}
const data = [
{
name: "Итоговый результат",
data: props.userData.traidingMonth
}
]
return (
<Chart
options={options}
series={data}
type="line"
height={280}
/>
)
}
export default FinacialResultChart
So you need to change your class to const, and push all your props (api data for example) into your children chart component. In chart options you can get the chart data with props.data

Split JSON into Multiple Array Series Highcharts

i get my JSON object from my php code in this format (JSONlint ok) :
[
[1375653600000,3.20104,175.00,116.00,11.00,31.00],[...],[1376776800000,2.85625,10.00,1.00,0.00,8.00]
]
i Have to split in 5 different series:
[1375653600000, 3.201014]
[1375653600000, 175.00]
[1375653600000, 116.00]
[1375653600000, 11.00]
[1375653600000, 31.00]
...
and (obviously) each array is for a different highcharts series.
i follow this post to get an idea about split the JSON:
Retrieving JSON data for Highcharts with multiple series?
This is my code:
$(function() {
// See source code from the JSONP handler at https://github.com/highslide-software/highcharts.com/blob/master/samples/data/from-sql.php
$.getJSON('grafico_nuovo.php?callback=?', function(data) {
// Add a null value for the end date
data = [].concat(data, [[Date.UTC(2012, 9, 14, 19, 59), null, null, null, null]]);
// create the chart
$('#container').highcharts('StockChart', {
chart : {
type: 'spline',
zoomType: 'xy'
},
navigator : {
adaptToUpdatedData: false,
series : {
data : data
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'analisi consumi e temperature'
},
subtitle: {
text: 'Analisi test solo temperatura media'
},
rangeSelector : {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 2,
text: '2d'
}, {
type: 'week',
count: 1,
text: '1w'
},{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: true, // it supports only days
selected : 2 // day
},
/*xAxis : {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},*/
xAxis: {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000, // one hour
type: 'datetime',
dateTimeLabelFormats: { minute: '%H:%M', day: '%A. %e/%m' },
// minRange: 15*60*1000,
//maxZoom: 48 * 3600 * 1000,
labels: {
rotation: 330,
y:20,
staggerLines: 1 }
},
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text: 'Consumo',
style: {
color: '#4572A7'
}
},
labels: {
format: '{value} Kw',
style: {
color: '#4572A7'
}
},
opposite: true
}],
series: [{
name: 'val1',
data: []
}, {
name: 'val2',
data: []
},
{
name: 'val3',
data: []
},
{
name: 'val4',
data: []
},
{
name: 'val5',
data: []
}]
});
});
});
/**
* Load new data depending on the selected min and max
*/
function afterSetExtremes(e) {
var currentExtremes = this.getExtremes(),
range = e.max - e.min,
chart = $('#container').highcharts();
chart.showLoading('Loading data from server...');
$.getJSON('grafico_nuovo.php?start='+ Math.round(e.min) +
'&end='+ Math.round(e.max) +'&callback=?', function(data) {
val1 = [];
val2 = [];
val3 = [];
val4 = [];
val5 = [];
$.each(data, function(key,value) {
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);
val3.push([value[0], value[3]]);
val4.push([value[0], value[4]]);
val5.push([value[0], value[5]]);
});
console.log('val1');
chart.series[0].setData(val1);
chart.series[1].setData(val2);
chart.series[2].setData(val3);
chart.series[3].setData(val4);
chart.series[4].setData(val5);
chart.hideLoading();
});
}
The navigator works fine (with little trouble after 3-4 clicks) but the other series doesn't show.
Everything should be ok, but i've probably missed something

Categories

Resources