Changing xaxis label from echarts library - javascript

var data = [];
var dataCount = 10;
var startTime = +new Date();
var categories = ['categoryA', 'categoryB', 'categoryC'];
var types = [
{name: 'JS Heap', color: '#7b9ce1'},
{name: 'Documents', color: '#bd6d6c'},
{name: 'Nodes', color: '#75d874'},
{name: 'Listeners', color: '#e0bc78'},
{name: 'GPU Memory', color: '#dc77dc'},
{name: 'GPU', color: '#72b362'}
];
// Generate mock data
echarts.util.each(categories, function (category, index) {
var baseTime = startTime;
for (var i = 0; i < dataCount; i++) {
var typeItem = types[Math.round(Math.random() * (types.length - 1))];
var duration = Math.round(Math.random() * 10000);
data.push({
name: typeItem.name,
value: [
index,
baseTime,
baseTime += duration,
duration
],
itemStyle: {
normal: {
color: typeItem.color
}
}
});
baseTime += Math.round(Math.random() * 2000);
}
});
function renderItem(params, api) {
var categoryIndex = api.value(0);
var start = api.coord([api.value(1), categoryIndex]);
var end = api.coord([api.value(2), categoryIndex]);
var height = api.size([0, 1])[1] * 0.6;
var rectShape = echarts.graphic.clipRectByRect({
x: start[0],
y: start[1] - height / 2,
width: end[0] - start[0],
height: height
}, {
x: params.coordSys.x,
y: params.coordSys.y,
width: params.coordSys.width,
height: params.coordSys.height
});
return rectShape && {
type: 'rect',
shape: rectShape,
style: api.style()
};
}
option = {
tooltip: {
formatter: function (params) {
return params.marker + params.name + ': ' + params.value[3] + ' ms';
}
},
title: {
text: 'Profile',
left: 'center'
},
dataZoom: [{
type: 'slider',
filterMode: 'weakFilter',
showDataShadow: false,
top: 400,
height: 10,
borderColor: 'transparent',
backgroundColor: '#e2e2e2',
handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
handleSize: 20,
handleStyle: {
shadowBlur: 6,
shadowOffsetX: 1,
shadowOffsetY: 2,
shadowColor: '#aaa'
},
labelFormatter: ''
}, {
type: 'inside',
filterMode: 'weakFilter'
}],
grid: {
height:300
},
xAxis: {
min: startTime,
scale: true,
axisLabel: {
formatter: function (val) {
return Math.max(0, val - startTime) + ' ms';
}
}
},
yAxis: {
data: categories
},
series: [{
type: 'custom',
renderItem: renderItem,
itemStyle: {
normal: {
opacity: 0.8
}
},
encode: {
x: [1, 2],
y: 0
},
data: data
}]
};
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!

First, create an array of dates like
var dates = ['2019-11-5','2019-10-3','2019-2-2','2019-1-4','2019-12-5'];
then in xAxis -> axisLabel return date
axisLabel: {
formatter: function (val,index) {
return dates[index];
}
}

Related

replace one amchart with another

Currently, I have this amchart below.
And I want to create another amchart with the same values. (I just want to replace the graph).
The new graphic is here -> https://www.amcharts.com/demos/line-graph/?theme=material#code
my code Angular:
prepareDataForTemplate(res) {
this.showLineChart = false;
if (res.RETURNCODE == 'OKK00') {
this.lines = [];
this.dataForChart.data.splice(0, this.dataForChart.data.length);
this.dataForChart.date.splice(0, this.dataForChart.date.length);
this.dataForChart.data.push(...res.HISTDEV.VALUE.map(x => x.COURS));
this.dataForChart.date.push(...res.HISTDEV.VALUE.map(x => x.DATE));
this.showLineChart = true;
if (res.HISTDEV.VALUE.length > 0) {
this.yMin = res.HISTDEV.VALUE[0].COURS;
this.yMax = res.HISTDEV.VALUE[0].COURS;
res.HISTDEV.VALUE.map(value => {
if (value.COURS < this.yMin) {
this.yMin = value.COURS;
}
if (value.COURS > this.yMax) {
this.yMax = value.COURS;
}
})
}
this.loadChart();
} else {
}
}
Then, the method loadChart(), it is the graph that I want to change...
loadChart() {
let datePipe = this.datePipe;
let decimalPipe = this.decimalPipe;
let leleuxNumPipe = this.leleuxNumPipe;
this.lineChartReturn = {
tooltip: {
trigger: 'axis',
position: function(pt) {
return [pt[0], '10%'];
},
formatter: function(params) {
return datePipe.transform(params[0].name) + "<br/>" +
params[0].marker + " " +
params[0].seriesName + " <b>" +
leleuxNumPipe.transform(decimalPipe.transform(params[0].value, '1.2-2')) + "</b";
}
},
title: {
left: 'center',
text: '',
},
xAxis: {
type: 'category',
boundaryGap: false,
//show: true,
data: this.dataForChart.date,
axisLabel: {
formatter: function(value, index) {
return datePipe.transform(value);
}
}
},
yAxis: {
type: 'value',
min: this.yMin,
max: this.yMax,
//show: true
axisLabel: {
formatter: function(value, index) {
return leleuxNumPipe.transform(decimalPipe.transform(value, '1.2-2'))
}
}
},
dataZoom: [{
type: 'inside',
start: 0,
end: 100
}, {
start: 0,
end: 10,
handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
handleSize: '80%',
handleStyle: {
color: '#fff',
shadowBlur: 3,
shadowColor: 'rgba(0, 0, 0, 0.6)',
shadowOffsetX: 2,
shadowOffsetY: 2
}
}],
series: [{
name: 'Amount',
type: 'line',
smooth: true,
symbol: 'none',
sampling: 'average',
itemStyle: {
color: 'rgba(255, 152, 0, .6)', // 'rgb(255, 70, 131)'
},
areaStyle: {
color: 'rgba(255, 152, 0, 0.15)',
origin: 'start'
},
lineStyle: {
// width: 1,
color: 'rgba(255, 152, 0, .6)',
},
data: this.dataForChart.data,
}, ]
};
}
In the doc amchart -> https://www.amcharts.com/demos/line-graph/?theme=material#code
I don't understand how to I adapt the code from amcharts with my method loadchart() ?
Sorry, if I ask you a lot
I'm pretty new to amcharts myself, but I'll give it a try.
First, I'm assuming that if you have a chart that you want to replace, you can save a reference to it, that would look something like this:
private chart: am4charts.XYChart;
And when you create your chart for the first time, wherever it is, you can do somthing like this:
this.chart = am4core.createFromConfig(this.lineChartReturn, 'htmlIdReference', am4charts.XYChart);
If your setup looks something like that, then you should be able to just use the dispose function, and then create it again with the new lineChartReturn you generate in loadChart
loadChart() {
if (this.chart) {
this.chart.dispose();
}
// your current code to generate new this.lineChartReturn
// Then just create it again using the createFromConfig
this.chart = am4core.createFromConfig(this.lineChartReturn, 'htmlIdReference', am4charts.XYChart);
}

Plotline (vertical line) in highcharts scatter chart

https://jsfiddle.net/7zL0v5oq/
I would like to have a plotline at today's date. The list can get quite long and in that case it helps with having an oversight. I fear it doesn't work because it is a scatter chart but I don't know what the problem is. I've searched all over the place but everything leads to plotlines, which clearly doesn't work. I would also be thankful if anyone knew, whether there was an easy way to filter my data the way I have it (standard highcharts filtering is deactivated but doesn't really help because of the static y values, so I get a huge, white space in the middle unless I filter at the edges. Thank you in advance for your help.
data = [{
"id": 1,
"release": "Software1",
"routine_failure_analysis_ended_on": null,
"sw_maintenance_releases_ended_on": "2014-04-01",
"sale_ended_on": "2013-04-01",
"security_vul_support_ended_on": "2015-04-01",
"service_contract_renewal_ended_on": null,
"svc_attach_ended_on": null,
"support_ended_on": "2018-03-31",
"updated_dates_on": "2012-10-03",
"created_at": "2018-05-04T18:53:21.301+02:00",
"updated_at": "2018-05-16T08:36:24.940+02:00"
},
{
"id": 2,
"release": "Software2",
"routine_failure_analysis_ended_on": null,
"sw_maintenance_releases_ended_on": "2019-07-24",
"sale_ended_on": "2017-07-31",
"security_vul_support_ended_on": "2020-07-24",
"service_contract_renewal_ended_on": null,
"svc_attach_ended_on": null,
"support_ended_on": "2022-07-31",
"updated_dates_on": "2015-08-14",
"created_at": "2018-05-05T04:00:44.170+02:00",
"updated_at": "2018-05-16T08:36:29.325+02:00"
},
{
"id": 3,
"release": "Software3",
"routine_failure_analysis_ended_on": null,
"sw_maintenance_releases_ended_on": "2018-03-01",
"sale_ended_on": "2017-03-01",
"security_vul_support_ended_on": "2018-12-01",
"service_contract_renewal_ended_on": null,
"svc_attach_ended_on": null,
"support_ended_on": "2022-02-28",
"updated_dates_on": "2016-09-02",
"created_at": "2018-05-05T04:00:44.401+02:00",
"updated_at": "2018-05-16T08:36:31.643+02:00"
}
];
const colors = ["#516", "#1781e3", "#25b252", "#20c997", "#ffc107", "#ff8b2e", "#dd1122"];
//Change to store y value paired to release/pid
var change = {};
//Which y values need to be displayed
var ticks = [0];
//Description of events
var sale = "Sale";
var support = "Support";
var svc = " SVC attach";
var sw = "Software maintenance";
var routine = "Routine failure analysis";
var service = "Service contract renewal";
var security = "Security vulnerability support";
//Data array for series
var high = [];
data.sort(function(a, b) {
return Date.parse(a.support_ended_on) < Date.parse(b.support_ended_on) ? 1 : -1
})
for (var i = 0; i < data.length; i++) {
var arr = [{
x: Date.parse(data[i].sale_ended_on),
y: (i + 1) * 20,
color: colors[0],
myValue: sale
},
{
x: Date.parse(data[i].sw_maintenance_releases_ended_on),
y: (i + 1) * 20,
color: colors[1],
myValue: sw
},
{
x: Date.parse(data[i].security_vul_support_ended_on),
y: (i + 1) * 20,
color: colors[2],
myValue: security
},
{
x: Date.parse(data[i].svc_attach_ended_on),
y: (i + 1) * 20,
color: colors[3],
myValue: svc
},
{
x: Date.parse(data[i].routine_failure_analysis_ended_on),
y: (i + 1) * 20,
color: colors[4],
myValue: routine
},
{
x: Date.parse(data[i].service_contract_renewal_ended_on),
y: (i + 1) * 20,
color: colors[5],
myValue: service
},
{
x: Date.parse(data[i].support_ended_on),
y: (i + 1) * 20,
color: colors[6],
myValue: support
}
];
var key, value;
line = [{
x: Date.parse(data[i].sale_ended_on),
y: (i + 1) * 20
}, {
x: Date.parse(data[i].support_ended_on),
y: (i + 1) * 20
}]
//Adding to change list, so we can add release/pid as label to y axis
key = (i + 1) * 20;
ticks.push(key);
if (data[i].pid) {
value = data[i].pid;
} else {
value = data[i].release;
}
change[key] = value;
//Expanding high (which is used for the highcharts series) with arr (all points for one pid)
if (data[i].pid) {
high.push({
label: data[i].pid,
name: data[i].pid,
type: 'scatter',
data: arr
}, {
type: 'line',
data: line,
linkedTo: ":previous"
});
} else {
high.push({
label: data[i].release,
name: data[i].release,
type: 'scatter',
data: arr,
showInLegend: false
}, {
type: 'line',
data: line,
linkedTo: ":previous"
});
}
}
Highcharts.chart("container", {
chart: {
height: data.length * 75
},
credits: {
enabled: false
},
yAxis: {
title: {
text: null
},
tickPositions: ticks,
visible: true,
labels: {
formatter: function() {
var value = change[this.value];
return value !== 'undefined' ? value : this.value;
}
}
},
xAxis: {
plotlines: [{
color: "#dd1122",
width: 2,
value: +new Date()
}],
type: 'datetime',
},
plotOptions: {
scatter: {
marker: {
symbol: 'circle',
radius: 7,
lineWidth: 2
}
},
line: {
enableMouseTracking: false,
marker: {
enabled: false
},
color: '#bbb',
lineWidth: 3
}
},
tooltip: {
formatter: function() {
var str = '<b>' + this.series.name + '</b><br/>'
if (this.point.myValue) {
str += this.point.myValue;
} else {
str += "Corrupted data!";
}
if (this.point.x < Date.parse(new Date))
return str += " ended on:<br/>" + Highcharts.dateFormat('%e %b %Y', new Date(this.x));
else
return str += " will end on:<br/>" + Highcharts.dateFormat('%e %b %Y', new Date(this.x));
},
shared: false
},
series: high
})
You have a typo, use plotLines instead of plotlines:
xAxis: {
plotLines: [{
...
}],
...
}
Live demo: https://jsfiddle.net/BlackLabel/p3u8ejtb/
API Reference: https://api.highcharts.com/highcharts/xAxis.plotLines

Shows a single chart on Highcharts

Hello I'm having a problem with my code in Highcharts I already declared my series but it only shows 1 set of chart. All data were set on var dataStr, on how the data that being put, I use push on every data that is being passed. So I think the problem is the with my push?
var dataStr = [
{name: 'JOB-182', problemReportCount: 0, totalCost: 50000, lostHour: 0, lostValue: 0},
{name: 'JOB-185', problemReportCount: 0, totalCost: 3432.65, lostHour: 0, lostValue: 0},
{name: 'JOB-188', problemReportCount: 4, totalCost: 5000, lostHour: 0, lostValue: 0},
{name: 'JOB-189', problemReportCount: 0, totalCost: 1000, lostHour: 0, lostValue: 0}
];
var jRefs = [];
var prJRefs = [];
var prLostVals = [];
var prLostHours = [];
var totCosts = [];
for (var i = 0; i < dataStr.length; i++) {
var jName = '' + dataStr[i].name;
if (jName != '') {
jRefs.push(jName);
var prCount = dataStr[i].problemReportCount;
if (prCount > 0) {
prJRefs.push(jName);
prLostVals.push(dataStr[i].lostValue);
prLostHours.push(dataStr[i].lostHour);
totCosts.push(dataStr[i].totalCost);
}
}
}
var genGraph = function() {
$("#backButton").hide();
$('#prGraph4').highcharts({
chart: {
type: 'column',
plotBackgroundColor: '#F7F7F7'
},
title: {
text: 'Problem Report'
},
subtitle: {
text: 'Estimated Lost Values'
},
xAxis: {
alternateGridColor: '#fff',
categories: prJRefs
},
yAxis: {
min: 0,
title: {
text: 'Amount'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold'
}
}
},
plotOptions: {
column: {
stacking: 'normal',
}
},
tooltip: {
shared: true,
formatter: function() {
var s = '<b>' + this.x + '</b>';
$.each(this.points, function() {
var lostValue = this.y;
s += '<br/><span style=" + dbl + "color:' + this.series.color + ';" + dbl + ">\u25CF</span> ' + this.series.name + ': <b>£</b> ' + lostValue.toFixed(2);
});
return s;
}
},
series:[{
name: 'Total Costs',
data: totCosts,
color: '#2ecc71',
stack: 'total'
}, {
name: 'Estimated Lost Materials Value',
data: prLostVals,
color: '#e74c3c',
stack: 'lost'
}, {
name: 'Estimated Lost Hours Price',
data: prLostHours,
color: '#e67e22',
stack: 'lost'
}]
});
};
Any help would be so much appreciated. Thanks!
You have only one visible column because only one set of data fulfills this condition:
if (prCount > 0) {
prJRefs.push(jName);
prLostVals.push(dataStr[i].lostValue);
prLostHours.push(dataStr[i].lostHour);
totCosts.push(dataStr[i].totalCost);
}
In addition, all values from series: Estimated Lost Materials Value and Estimated Lost Hours Price are 0.
Live demo: http://jsfiddle.net/BlackLabel/vu9ahfk5/

jqplot chart with data from variable and data from JSON

I'm trying to load data into a jqplot chart via variable, but it's only displaying the first value. I'm lost at to why is doing this.
JavaScript:
$(document).ready(function () {
var sin = [[20, 10, 0, 10, 15, 25, 35, 50, 48, 45, 35, 30, 15, 10]];
var plot = $.plot($(".chart"),
[{ data: sin, label: "sin(x)", color: "#ee7951" }], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 60 }
});
var previousPoint = null;
$(".chart").bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$('#tooltip').fadeOut(200, function () {
$(this).remove();
});
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
maruti.flot_tooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y);
}
} else {
$('#tooltip').fadeOut(200, function () {
$(this).remove();
});
previousPoint = null;
}
});
});
maruti = {
flot_tooltip: function (x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
top: y + 5,
left: x + 5
}).appendTo("body").fadeIn(200);
}
}
</script>
Ultimately, I would prefer to use JSON format data and use the first value for the chart and the second for the axis.
Data:
[["50.00","3/18/2015 2:00:00 PM"],["37.00","3/12/2015 3:42:44 PM"],["35.00","3/11/2015 3:42:44 PM"]]
Any recommendations or link to samples using this type of data would be greatly appreciated.
The string format was wrong. I ended up using Entity Framework.
So my code behind looks something like:
using (myEntities myEntitiesContainer = new myEntities())
{
var alldata = myEntitiesContainer.myData(id).ToList();
foreach (myData i in alldata)
{
if (alldata.IndexOf(i) == alldata.Count - 1)
{
sb.Append("['").Append(i.DateData.ToString("yyyy-MM-dd HH:mmtt")).Append("', ").Append(i.SomeData.ToString()).Append("]");
}
else
{
sb.Append("['").Append(i.DateData.ToString("yyyy-MM-dd HH:mmtt")).Append("', ").Append(i.SomeData.ToString()).Append("], ");
}
}
myReturnString = sb.ToString();
}
The return string:
[['2015-03-31 16:00PM', 30.00], ['2015-03-31 14:00PM', 40.00], ['2015-03-31 13:00PM', 50.00]]
The Javascript looks like:
var renderGraph = function () {
var plot
var line1 =
plot = $.jqplot('chart', [line1], {
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: { min: 0, formatString: '%b %#d' },
tickInterval: '1 day'
},
yaxis: {
tickOptions:{ formatString: '%d'}
}
},
highlighter: {
show: true,
yvalues: 1,
xvalues: 1,
formatString: 'Date: %s Level: %s'
},
cursor: {
show: false,
tooltipLocation: 'sw'
},
legend: {
show: false
}
});
}

Restacking cumulative columns in Highcharts marimekko charts

I've got a basic variable width column chart (aka Marimekko) set up using Highcharts but am having trouble getting it to restack the columns properly to eliminate the data gap once a series has been removed or hidden.
JSFIDDLE DEMO <-- I've set up a demo of the issue here.
You'll notice clicking on a legend item removes the series from the chart, but it also removes all of the following data points in the array (i.e. clicking on series C removes series C, D, and E whereas it should redraw to A-B-D-E). Since the y-axis data is meant to display a cumulative sum of all series, these should re-shuffle as adjacent columns with no gaps. How can I get this to render properly?
THIS POST uses similar demo code and attempting to solve the same problem, however the answer is somewhat elusive and I am unable to get it working.
Thanks in advance!
$(function () {
var dataArray = [
{ name: 'A', x: 200, y: 120 },
{ name: 'B', x: 380, y: 101 },
{ name: 'C', x: 450, y: 84 },
{ name: 'D', x: 198, y: 75 },
{ name: 'E', x: 95, y: 55 }
];
function makeSeries(listOfData) {
var sumX = 0.0;
for (var i = 0; i < listOfData.length; i++) {
sumX += listOfData[i].x;
}
var allSeries = []
var x = 0.0;
for (var i = 0; i < listOfData.length; i++) {
var data = listOfData[i];
allSeries[i] = {
name: data.name,
data: [
[x, 0], [x, data.y],
{
x: x + data.x / 2.0,
y: data.y,
dataLabels: { enabled: false, format: data.x + ' x {y}' }
},
[x + data.x, data.y], [x + data.x, 0]
],
w: data.x,
h: data.y
};
x += data.x + 0;
}
return allSeries;
}
$('#container').highcharts({
chart: { type: 'area' },
xAxis: {
tickLength: 0,
labels: { enabled: true}
},
yAxis: {
title: { enabled: false}
},
plotOptions: {
series: {
events: {
legendItemClick: function () {
var pos = this.index;
var sname = this.name;
var chart = $('#container').highcharts();
while(chart.series.length > 0) {
chart.series[pos].remove(true);
}
dataArray[pos]= { name: sname, x: 0, y: 0 };
chart.series[0].setData(dataArray);
}
}
},
area: {
lineWidth: 0,
marker: {
enabled: false,
states: {
hover: { enabled: false }
}
}
}
},
series: makeSeries(dataArray)
});
});

Categories

Resources