Filling JSON content from database - javascript

I tried for hours before asking you for help. I'm so sorry for wasting your time. But please help me, I'm really hungry to learn. I'm sorry for my bad english.
https://www.amcharts.com/demos/column-chart-images-top/
I am working on a project with MVC entities(Mysql). I want to fill the contents of this chart with A1(string) and A2(int) fields of table A.
Thank You.
am5.ready(function () {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("Personel_Grafik");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: "none",
wheelY: "none"
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {}));
cursor.lineY.set("visible", false);
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xRenderer = am5xy.AxisRendererX.new(root, { minGridDistance: 30 });
var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
maxDeviation: 0,
categoryField: "name",
renderer: xRenderer,
tooltip: am5.Tooltip.new(root, {})
}));
xRenderer.grid.template.set("visible", false);
var yRenderer = am5xy.AxisRendererY.new(root, {});
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation: 0,
min: 0,
extraMax: 0.1,
renderer: yRenderer
}));
yRenderer.grid.template.setAll({
strokeDasharray: [2, 2]
});
// Create series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Series 1",
xAxis: xAxis,
yAxis: yAxis,
valueYField: "value",
sequencedInterpolation: true,
categoryXField: "name",
tooltip: am5.Tooltip.new(root, { dy: -25, labelText: "{valueY}" })
}));
series.columns.template.setAll({
cornerRadiusTL: 5,
cornerRadiusTR: 5
});
series.columns.template.adapters.add("fill", (fill, target) => {
return chart.get("colors").getIndex(series.columns.indexOf(target));
});
series.columns.template.adapters.add("stroke", (stroke, target) => {
return chart.get("colors").getIndex(series.columns.indexOf(target));
});
// Set data
var data = [
{
name: "John",
value: 35654,
bulletSettings: { src: "https://www.amcharts.com/lib/images/faces/A04.png" }
},
{
name: "Damon",
value: 65456,
bulletSettings: { src: "https://www.amcharts.com/lib/images/faces/C02.png" }
},
{
name: "Patrick",
value: 45724,
bulletSettings: { src: "https://www.amcharts.com/lib/images/faces/D02.png" }
},
{
name: "Mark",
value: 13654,
bulletSettings: { src: "https://www.amcharts.com/lib/images/faces/E01.png" }
}
];
series.bullets.push(function () {
return am5.Bullet.new(root, {
locationY: 1,
sprite: am5.Picture.new(root, {
templateField: "bulletSettings",
width: 50,
height: 50,
centerX: am5.p50,
centerY: am5.p50,
shadowColor: am5.color(0x000000),
shadowBlur: 4,
shadowOffsetX: 4,
shadowOffsetY: 4,
shadowOpacity: 0.6
})
});
});
xAxis.data.setAll(data);
series.data.setAll(data);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear(1000);
chart.appear(1000, 100);
}); // end am5.ready()
#Personel_Grafik {
width: 100%;
height: 265px;
}
<div id="Personel_Grafik2"></div>

Related

amCharts5 - remove crosshairs from tooltip?

I'm making a simple bubble chart using amCharts5. The library has a built in tooltip that looks like a crosshair, I'd like to remove the crosshair lines but keep the tooltip. I haven't been able to find a way to accomplish this.
See the code snippets below for a demonstration of what the crosshairs look like, here's a codepen as well.
I tried adding these lines, per the docs:
cursor.lineY.setAll({
visible: false
cursor.lineX.setAll({
visible: false
});
The result was that the cross-hair lines were hidden, but the little tooltips that show up at the end of each crosshair still showed up, which looked confusing and weird.
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelY: "zoomXY",
pinchZoomX:true,
pinchZoomY:true
}));
chart.get("colors").set("step", 2);
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererX.new(root, { minGridDistance: 50 }),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {}),
tooltip: am5.Tooltip.new(root, {})
}));
// Create series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.LineSeries.new(root, {
calculateAggregates: true,
xAxis: xAxis,
yAxis: yAxis,
valueYField: "y",
valueXField: "x",
valueField: "value",
tooltip: am5.Tooltip.new(root, {
labelText: "x: {valueX}, y: {valueY}, value: {value}, name: {name}"
})
}));
// Add bullet (add circles that appear on the chart)
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
var circleTemplate = am5.Template.new({});
series.bullets.push(function() {
var graphics = am5.Circle.new(root, {
fill: series.get("fill"),
}, circleTemplate);
return am5.Bullet.new(root, {
sprite: graphics
});
});
series.strokes.template.set("strokeOpacity", 0);
// Add cursor \\
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis,
yAxis: yAxis,
snapToSeries: [series]
}));
// Sample data
var data = [{
"y": 69,
"x": 1,
"value": 69,
"name": "sue"
}, {
"y": 69,
"x": 2,
"value": 69,
"name": "john"
}, ]
series.data.setAll(data);
chart.appear(1000, 100);
#chartdiv {
width: 100%;
max-width: 100%;
height: 250px;
}
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<div id="chartdiv"></div>
1. Remove the cursor entirely
Delete this piece of code:
chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis,
yAxis: yAxis,
snapToSeries: [series]
}));
Remove tooltip declaration from axes settings:
tooltip: am5.Tooltip.new(root, {})
2. Move the remaining tooltip declaration from series to bullets
You do not need this tooltip:
var series = chart.series.push(am5xy.LineSeries.new(root, {
// ...
tooltip: am5.Tooltip.new(root, {
labelText: "x: {valueX}, y: {valueY}, value: {value}, name: {name}"
})
}));
Instead, do that:
var circleTemplate = am5.Template.new({});
series.bullets.push(function() {
var graphics = am5.Circle.new(root, {
fill: series.get("fill"),
tooltipText: "x: {valueX}, y: {valueY}, value: {value}, name: {name}" // <--- HERE
}, circleTemplate);
return am5.Bullet.new(root, {
sprite: graphics
});
});
Here is your snippet with these little modifications:
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelY: "zoomXY",
pinchZoomX:true,
pinchZoomY:true
}));
chart.get("colors").set("step", 2);
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererX.new(root, { minGridDistance: 50 })
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
// Create series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.LineSeries.new(root, {
calculateAggregates: true,
xAxis: xAxis,
yAxis: yAxis,
valueYField: "y",
valueXField: "x",
valueField: "value"
}));
// Add bullet (add circles that appear on the chart)
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
var circleTemplate = am5.Template.new({});
series.bullets.push(function() {
var graphics = am5.Circle.new(root, {
fill: series.get("fill"),
tooltipText: "x: {valueX}, y: {valueY}, value: {value}, name: {name}" // <--- HERE
}, circleTemplate);
return am5.Bullet.new(root, {
sprite: graphics
});
});
series.strokes.template.set("strokeOpacity", 0);
// Sample data
var data = [{
"y": 69,
"x": 1,
"value": 69,
"name": "sue"
}, {
"y": 69,
"x": 2,
"value": 69,
"name": "john"
}, ]
series.data.setAll(data);
chart.appear(1000, 100);
#chartdiv {
width: 100%;
max-width: 100%;
height: 250px;
}
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<div id="chartdiv"></div>

Amcharts5: legend errors in multiline chart

I am using amchart5 to render some multi line data and I have some issues with how the data is being rendered.
I cannot add currency symbols to the labels of the y-axis
I cant turn the labels of the x-axis so they are more vertical rather than horizontal
The preview will not show any lines
How can I resolve this?
See image:
Javascript
<script type="text/javascript">
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("fundChartLine");
root.numberFormatter.setAll({
numberFormat: "#,###.##00",
});
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root),
am5themes_Responsive.new(root),
Amdg.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/percent-charts/pie-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
pinchZoomX:true
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
behavior: "none"
}));
cursor.lineY.set("visible", false);
// Define data
var data = {{ line_chart_data| safe }}
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
// Create Y-axis
let yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
// Create X-Axis
/*var xAxis = chart.xAxes.push(
am5xy.CategoryAxis.new(root, {
maxDeviation: 0.2,
renderer: am5xy.AxisRendererX.new(root, {}),
categoryField: "chart_dates"
})
);
xAxis.data.setAll(data);*/
var xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
minGridDistance: 30
})
})
);
xAxis.get("dateFormats")["day"] = "MM/dd";
xAxis.get("periodChangeDateFormats")["day"] = "MMMM";
xAxis.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/line-series/
function createSeries(name, field) {
var series = chart.series.push(
am5xy.LineSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: field,
categoryXField: "chart_dated_dt",
stacked: false
//legendLabelText: "[{fill}]{category}[/]",
//legendValueYText: "[bold {fill}]ZAR{valueY}[/]"
})
);
series.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
series.fills.template.setAll({
fillOpacity: 0.5,
visible: false
});
series.data.setAll(data);
//series.labels.template.set("visible", false);
//series.ticks.template.set("visible", false);
console.log(series)
}
chart.topAxesContainer.children.push(am5.Label.new(root, {
text: "Performance",
fontSize: 30,
fontColor: '#e40505',
fontWeight: "500",
textAlign: "center",
x: am5.percent(50),
centerX: am5.percent(50),
paddingTop: 0,
paddingBottom: 20,
}));
createSeries("Average Contributions", "average_contrib");
createSeries("Average Contributions + Interest", "average_totals");
createSeries("Median Contributions", "median_contrib");
createSeries("Median Contributions + Interest", "median_totals");
createSeries("Your Contributions", "user_contrib");
createSeries("Your Contributions + Interest", "user_totals");
//var legend = chart.children.push(am5.Legend.new(root, {}));
//legend.data.setAll(chart.series.values);
var legend = chart.bottomAxesContainer.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
useDefaultMarker: true,
paddingTop: 10,
paddingBottom: 20,
layout: am5.GridLayout.new(root, {
maxColumns: 3,
fixedWidthGrid: true
})
}));
legend.data.setAll(chart.series.values);
// Add scrollbar
// https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/
/*var scrollbarX = am5.Scrollbar.new(root, {
orientation: "horizontal"
});*/
var scrollbarX = am5xy.XYChartScrollbar.new(root, {
orientation: "horizontal",
height: 50
});
//chart.bottomAxesContainer.children.push(scrollbarX);
/*let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.CategoryAxis.new(root, {
maxDeviation: 0.2,
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
}),
categoryField: "chart_dates"
})
);*/
let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
groupIntervals: [{ timeUnit: "year", count: 1 }],
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
})
})
);
let sbyAxis = scrollbarX.chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
let sbseries = scrollbarX.chart.series.push(
am5xy.LineSeries.new(root, {
xAxis: sbxAxis,
yAxis: sbyAxis,
valueYField: "user_totals",
valueXField: "chart_dated_dt",
})
);
sbseries.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
sbseries.data.setAll(data);
chart.set("scrollbarX", scrollbarX);
console.log(sbseries.data.values[0]["user_totals"])
console.log(sbseries.data.values[0]["chart_dated_dt"])
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
root._logo.dispose();
chart.appear(1000, 100);
}); // end am5.ready()
I've looked at the docs and at some questions here and still stuck-
For the currency I added the currency symbol within the number formatter:
root.numberFormatter.setAll({
numberFormat: "'ZAR '#,###.##00",
tooltipNumberFormat: "'ZAR '#,###.##00",
I didn't figure out how to handle the formatting of the legend but what I did instead was change the date data from a Category value with a string to a an actual which allowed me to change the axis into a date one. Amcharts naturally handles the formatting of this in such a way that my problem disappeared and it also fit my long terms data goals for the chart. The category was a story gap.
The preview had isues with my date compile. I noticed in the code when converting the date I was simply making the date object but not actually getting the time. By using the the get_time i was able to properly render the x-axis. This issue aslo affected number 2.
for (let i = 0; i < data.length; i++) {
data[i]["chart_dated_dt"] = new Date(data[i]["chart_dated_dt"]).getTime();
}
Full code:
<script type="text/javascript">
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("fundChartLine");
root.numberFormatter.setAll({
numberFormat: "'ZAR '#,###.##00",
tooltipNumberFormat: "'ZAR '#,###.##00",
});
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root),
am5themes_Responsive.new(root),
Amdg.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/percent-charts/pie-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
pinchZoomX:true
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
behavior: "none"
}));
cursor.lineY.set("visible", false);
// Define data
var data = {{ line_chart_data| safe }}
for (let i = 0; i < data.length; i++) {
data[i]["chart_dated_dt"] = new Date(data[i]["chart_dated_dt"]).getTime();
}
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
// Create Y-axis
let yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
maxDeviation: 0.1,
renderer: am5xy.AxisRendererY.new(root, {})
})
);
var xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
maxDeviation: 0.1,
groupData: true,
groupIntervals: [
{ timeUnit: "month", count: 1 }
],
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
}),
tooltip: am5.Tooltip.new(root, {})
})
);
xAxis.get("dateFormats")["day"] = "MM/dd";
xAxis.get("periodChangeDateFormats")["day"] = "MMMM";
xAxis.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/line-series/
function createSeries(name, field) {
var series = chart.series.push(
am5xy.LineSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: field,
valueXField: "chart_dated_dt",
stacked: false,
tooltip: am5.Tooltip.new(root, {
pointerOrientation: "horizontal",
labelText: "{valueY}",
})
})
);
series.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
series.fills.template.setAll({
fillOpacity: 0.5,
visible: false
});
series.data.setAll(data);
}
chart.topAxesContainer.children.push(am5.Label.new(root, {
text: "Performance",
fontSize: 30,
fontColor: '#e40505',
fontWeight: "500",
textAlign: "center",
x: am5.percent(50),
centerX: am5.percent(50),
paddingTop: 0,
paddingBottom: 20,
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis
}));
cursor.lineY.set("visible", false);
createSeries("Average Contributions", "average_contrib");
createSeries("Average Contributions + Interest", "average_totals");
createSeries("Median Contributions", "median_contrib");
createSeries("Median Contributions + Interest", "median_totals");
createSeries("Your Contributions", "user_contrib");
createSeries("Your Contributions + Interest", "user_totals");
var legend = chart.bottomAxesContainer.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
useDefaultMarker: true,
paddingTop: 10,
paddingBottom: 20,
layout: am5.GridLayout.new(root, {
maxColumns: 3,
fixedWidthGrid: true
})
}));
legend.data.setAll(chart.series.values);
// Add scrollbar
// https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/
var scrollbarX = am5xy.XYChartScrollbar.new(root, {
orientation: "horizontal",
height: 50
});
let sbxAxis = scrollbarX.chart.xAxes.push(
am5xy.DateAxis.new(root, {
groupData: true,
groupIntervals: [
{ timeUnit: "month", count: 1 }
],
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {
opposite: false,
strokeOpacity: 0
})
})
);
let sbyAxis = scrollbarX.chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
})
);
let sbseries = scrollbarX.chart.series.push(
am5xy.LineSeries.new(root, {
xAxis: sbxAxis,
yAxis: sbyAxis,
valueYField: "user_totals",
valueXField: "chart_dated_dt",
})
);
sbseries.strokes.template.setAll({
strokeWidth: 2,
//strokeDasharray: [2,1]
});
sbseries.data.setAll(data);
chart.set("scrollbarX", scrollbarX);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
sbseries.appear(1000, 100);
console.log(chart.series)
console
root._logo.dispose();
chart.appear(1000, 100);
}); // end am5.ready()
</script>

echart data point gradient color

I am trying to make a gradient line chart, The issue is with tooltip legend color and color of data points, they appear in brown gradient which was the default.
I was able to change the tooltip color, anyhow that is not the actual data point color but able to fix it to one color at least. whereas the points on the line do not pick up the color of the line.
Can someone point me in right direction?
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
var option;
var data = [["2020-06-05",116],["2020-06-06",129],["2020-06-07",135],["2020-06-08",86],["2020-06-09",73],["2020-06-10",85],["2020-06-11",73],["2020-06-12",68],["2020-06-13",92],["2020-06-14",130],["2020-06-15",245],["2020-06-16",139],["2020-06-17",115],["2020-06-18",111],["2020-06-19",309],["2020-06-20",206],["2020-06-21",137],["2020-06-22",128],["2020-06-23",85],["2020-06-24",94],["2020-06-25",71],["2020-06-26",106],["2020-06-27",84],["2020-06-28",93],["2020-06-29",85],["2020-06-30",73],["2020-07-01",83],["2020-07-02",125],["2020-07-03",107],["2020-07-04",82],["2020-07-05",44],["2020-07-06",72],["2020-07-07",106],["2020-07-08",107],["2020-07-09",66],["2020-07-10",91],["2020-07-11",92],["2020-07-12",113],["2020-07-13",107],["2020-07-14",131],["2020-07-15",111],["2020-07-16",64],["2020-07-17",69],["2020-07-18",88],["2020-07-19",77],["2020-07-20",83],["2020-07-21",111],["2020-07-22",57],["2020-07-23",55],["2020-07-24",60]];
var dateList = data.map(function (item) {
return item[0];
});
var valueList = data.map(function (item) {
return item[1];
});
option = {
color: {
type: 'linear',
x: 0, y: 1,x2:0,y2:0,
colorStops: [{
offset: 0, color: '#00d4ff' // color at 0% position
}, {
offset: 1, color: '#090979' // color at 100% position
}],
global:true
},
// Make gradient line here
visualMap: [{
show: true,
type: 'continuous',
seriesIndex: 0,
min: 0,
max: 400
}],
title: [{
left: 'center',
text: 'Gradient along the y axis'
}],
xAxis: [{
data: dateList,
axisPointer: {
label:{
color:['#5470c6'],
}
},
axisLabel: {
formatter: function (value) {
return moment(value).format("MMM YY");
// And other formatter tool (e.g. moment) can be used here.
}
}
}],
yAxis: [{
type: 'value',
axisPointer: {
label:{
color:['#5470c6'],
}
}
}],
grid: [{
width:'auto',
height:'auto'
}],
tooltip : {
trigger: 'axis',
axisPointer: {
animation: true,
},
formatter: function (params) {
var colorSpan = color => '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + color + '"></span>';
let rez = '<p>' + params[0].axisValue + '</p>';
console.log(params); //quite useful for debug
params.forEach(item => {
// console.log(item); //quite useful for debug
var xx = '<p>' + colorSpan('#00d4ff') + ' ' + item.seriesName + ': ' + item.data + '</p>'
rez += xx;
});
console.log(rez);
return rez;
}
},
series: [{
color:['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
type: 'line',
showSymbol: false,
data: valueList,
// smooth: true,
label:{
show:true,
position:'top'
},
lineStyle:{
color: {
type: 'linear',
x: 0, y: 1,x2:0,y2:0,
colorStops: [{
offset: 0, color: '#00d4ff' // color at 0% position
}, {
offset: 1, color: '#090979' // color at 100% position
}],
global:false
}
}
}]
};
console.log(myChart);
if (option && typeof option === 'object') {
myChart.setOption(option);
}
You need to add gradientColor array to echarts options. Now echart will take care of changing color of tooltip and data point. You can also remove your custom tooltip formatted function.
gradientColor: ["#00d4ff", "#090979"]
Here the complete options object:
var data = [];
var dateList = data.map(function(item) {
return item[0];
});
var valueList = data.map(function(item) {
return item[1];
});
option = {
gradientColor: ["#00d4ff", "#090979"],
// Make gradient line here
visualMap: [
{
show: true,
type: "continuous",
seriesIndex: 0,
min: 0,
max: 400
}
],
title: [
{
left: "center",
text: "Gradient along the y axis"
}
],
xAxis: [
{
data: dateList,
axisPointer: {
label: {
color: ["#5470c6"]
}
},
axisLabel: {
formatter: function(value) {
return moment(value).format("MMM YY");
// And other formatter tool (e.g. moment) can be used here.
}
}
}
],
yAxis: [
{
type: "value",
axisPointer: {
label: {
color: ["#5470c6"]
}
}
}
],
grid: [
{
width: "auto",
height: "auto"
}
],
tooltip: {
trigger: "axis",
axisPointer: {
animation: true
}
},
series: [
{
type: "line",
showSymbol: false,
data: valueList,
// smooth: true,
label: {
show: true,
position: "top"
}
}
]
};

Simplify JavaScript array variable

I'm looking to simplify this code. Any way to it so? Spring MVC + Apex Charts
var d = /*[[${s0}]]*/ null`; <-- It is sent via the Spring Framework. Basically represents datetime(in millis) at `d[0]`, `d[3]`,... Temperature at `d[1]`, `d[4]`,... and Humidity at `d[2]`, `d[5]`,...
<script type="text/javascript" th:inline="javascript">
var d = /*[[${s0}]]*/ null;
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: [
[d[0], d[1]],
[d[3], d[4]],
[d[6], d[7]],
[d[9], d[10]],
[d[12], d[13]],
[d[15], d[16]],
[d[18], d[19]],
[d[21], d[22]],
[d[24], d[25]],
[d[27], d[28]],
[d[30], d[31]],
[d[33], d[34]],
[d[36], d[37]],
[d[39], d[40]],
[d[42], d[43]],
[d[45], d[46]],
[d[48], d[49]],
[d[51], d[52]],
[d[54], d[55]],
[d[57], d[58]],
[d[60], d[61]],
[d[63], d[64]],
[d[66], d[67]],
[d[69], d[70]]
]
},
{
name: "Humidity",
data: [
[d[0], d[2]],
[d[3], d[5]],
[d[6], d[8]],
[d[9], d[11]],
[d[12], d[14]],
[d[15], d[17]],
[d[18], d[20]],
[d[21], d[23]],
[d[24], d[26]],
[d[27], d[29]],
[d[30], d[32]],
[d[33], d[35]],
[d[36], d[38]],
[d[39], d[41]],
[d[42], d[44]],
[d[45], d[47]],
[d[48], d[50]],
[d[51], d[53]],
[d[54], d[56]],
[d[57], d[59]],
[d[60], d[62]],
[d[63], d[65]],
[d[66], d[68]],
[d[69], d[71]]
]
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();
</script>
I just need to simplify sending data via d[0], d[1] etc. Is there any kind of loop or anything else I can use?
You could take a function which takes the data and a pattern for the wanted elements and an offset for increment for the next row.
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
result = { series: [
{ name: 'Temperature', data: mapByPattern(data, [0, 1], 3) },
{ name: "Humidity", data: mapByPattern(data, [0, 2], 3) }
]};
console.log(result);
Thank You, Nina. Code code didn't work exactly as i wanted but was so helpful to fix my own. Thanks alot! Here's some fixed code :)
var data = /*[[${s0}]]*/ null;
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: mapByPattern(data, [0, 1], 3)
},
{
name: "Humidity",
data: mapByPattern(data, [0, 2], 3)
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();

Change highcharts data label position

This is my jsfiddle link http://jsfiddle.net/bb1m6xyk/1/
I want that all my labels like my data: 0 etc are positioned at the base and in center of each zone.
$('#container').highcharts({
chart: {
type: 'area'
},
yAxis: {
title: {
text: 'Percent'
}
},
plotOptions: {
area: {
enableMouseTracking: false,
showInLegend: false,
stacking: 'percent',
lineWidth: 0,
marker: {
enabled: false
},
dataLabels: {
className:'highlight',
enabled: true,
formatter: function () {
console.log(this);
return this.point.myData
}
}
}
},
series: [{
name: 'over',
color: 'none',
data: overData
}, {
id: 's1',
name: 'Series 1',
data: data,
showInLegend: true,
zoneAxis: 'x',
zones: zones
}]
});
Is this possible? I tried it using className on dataLabels but it doesn't take that into effect.
Any help is appreciated.
There are a few ways to render labels on a chart.
The Renderer
Live example: http://jsfiddle.net/11rj6k6p/
You can use Renderer.label to render the label on the chart - this is a low level approach but it gives you full control how the labels will be rendered. You can loop the zones and set x and y attributes of the labels, e.g. like this:
const labels = ['l1', 'l2', 'l3', 'l4', 'l5']
function drawLabels() {
const zonesLabels = this.zonesLabels
const series = this.get('s1')
const { yAxis, xAxis } = series
const y = yAxis.toPixels(0) - 20 // -20 is an additional offset in px
series.zones.reduce((prev, curr, i) => {
if (curr.value !== undefined) {
const x = (xAxis.toPixels(prev.value) + xAxis.toPixels(curr.value)) / 2
if (!zonesLabels[i]) {
zonesLabels.push(
this.renderer.label(labels[i], x, y).add().attr({
align: 'center',
zIndex: 10
})
)
} else {
zonesLabels[i].attr({ x, y })
}
}
return curr
}, { value: series.dataMin })
}
Then set the function on load - to render the labels, and on redraw - to reposition the labels if the chart size changed.
chart: {
type: 'area',
events: {
load: function() {
this.zonesLabels = []
drawLabels.call(this)
},
redraw: drawLabels
}
},
The annotations module
Live example: http://jsfiddle.net/a5gb7aqz/
If you do not want to use the Renderer API, you can use the annotations module which allows to declare labels in a chart config.
Add the module
<script src="https://code.highcharts.com/modules/annotations.js"></script>
Map zones to the labels config object
const labels = ['l1', 'l2', 'l3', 'l4', 'l5']
function annotationsLabels() {
const zonesLabels = []
zones.reduce((prev, curr, i) => {
zonesLabels.push({
text: labels[i],
point: {
x: (prev.value + curr.value) / 2,
y: 0,
xAxis: 0,
yAxis: 0
}
})
return curr
}, { value: 0 })
return zonesLabels
}
Set the annotations options
annotations: [{
labels: annotationsLabels(),
labelOptions: {
shape: 'rect',
backgroundColor: 'none',
borderColor: 'none',
x: 0,
y: 0
}
}],
Data labels and a new series
Live example: http://jsfiddle.net/wpk1495g/
You can create a new scatter series which will not respond to mouse events and it won't be visible in the legend. The labels can be displayed as data labels.
Map zones to series points
const labels = ['l1', 'l2', 'l3', 'l4', 'l5']
function seriesData() {
const points = []
zones.reduce((prev, curr, i) => {
points.push( {
x: (prev.value + curr.value) / 2,
y: 50,
dataLabels: {
enabled: true,
format: labels[i]
}
})
return curr
}, { value: 0 })
return points
}
Set the series options in the chart config
, {
type: 'scatter',
enableMouseTracking: false,
showInLegend: false,
data: seriesData(),
zIndex: 10,
color: 'none',
dataLabels: { style: { textOutline: false }, x: 0, y: 0 }
}
Output

Categories

Resources