amcharts5 - chart above another chart using same xaxis? - amcharts

I am attempting to show a column chart (or a line chart would work too) above a gannt chart using the same xaxis (timestamp) and having trouble with spacing as well as getting any data to show in the column chart. I don't even know if this is possible to do, but the help docs made it sound like it was so I am more than likely missing quite a few things in the configuration or doing things wrong.
I've created a codepen with what I have so far. The original gannt chart shows fine, then I am able to get the column chart's yaxis to show (although it overlaps the gannt instead of being above it and does not show any data).
Any assistance/explanation with this would be appreciated.
// Set data
var data = [{
"State": "Idle",
"Start": 1424321864000,
"End": 1424321875000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424322649000,
"End": 1424322669000,
"Duration": 20
}, {
"State": "Idle",
"Start": 1424322970000,
"End": 1424322981000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424323093000,
"End": 1424323139000,
"Duration": 46
}, {
"State": "Active",
"Start": 1424323250000,
"End": 1424323268000,
"Duration": 18
}, {
"State": "Idle",
"Start": 1424323680000,
"End": 1424323703000,
"Duration": 23
}];
var mousekeys = [{
"Timestamp": 1424318400000,
"Clicks": "20",
"Keypresses": "30"
}];
/**
* ---------------------------------------
* This demo was created using amCharts 5.
*
* For more information visit:
* https://www.amcharts.com/
*
* Documentation is available at:
* https://www.amcharts.com/docs/v5/
* ---------------------------------------
*/
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
//font size theme
var myTheme = am5.Theme.new(root);
myTheme.rule("Label").setAll({
fontSize: 12
});
root.setThemes([
am5themes_Animated.new(root),
myTheme
]);
root.locale = am5locales_en_US;
//chartReg['chart'].utc = true; //force chart to show in UTC instead of device timezone
root.timezone = am5.Timezone.new('UTC'); //user timezone
//duration format
root.durationFormatter.setAll({
baseUnit: "second",
durationFormat: "hh'h' mm'm' ss's'"
});
//create chart
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: false,
wheelY: false,
layout: root.verticalLayout,
marginTop: 0,
marginRight: 0,
marginBottom: 0,
marginLeft: 0,
paddingTop: 0,
paddingRight: 20,
paddingBottom: 20,
paddingLeft: 10,
}));
//zoom button
//chart.zoomOutButton.setAll({
// forceHidden: true, //disables zoom button
//});
chart.zoomOutButton.get("background").setAll({
fill: am5.color("#BDBDBD"),
});
chart.zoomOutButton.get("background").states.create("hover", {}).setAll({
fill: am5.color("#8a8a8a"),
});
chart.zoomOutButton.get("background").states.create("down", {}).setAll({
fill: am5.color("#707070"),
});
chart.zoomOutButton.get("background").states.create("active", {}).setAll({
fill: am5.color("#707070"),
});
//create axes
var yAxis = chart.yAxes.push(am5xy.CategoryAxis.new(root, {
text: "State",
fontWeight: "500",
height: am5.percent(70),
categoryField: "State",
renderer: am5xy.AxisRendererY.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
}));
var yAxis2 = chart.yAxes.push(am5xy.ValueAxis.new(root, {
text: "Clicks",
fontWeight: "500",
height: am5.percent(30),
min: 0, //min 'hint', but not forced
//strictMinMax: true, //forces the min/max
//extraMax: 0.1, //extra 10% to the value range which acts as 'padding' to the yaxis
renderer: am5xy.AxisRendererY.new(root, {})
}));
//the order is top to bottom ends up bottom to top on the chart
yAxis.data.setAll([
{ State: "Idle" },
{ State: "Active" }
]);
//y-axis dash lines
var yRenderer = yAxis.get("renderer");
yRenderer.grid.template.setAll({
strokeDasharray: [6]
});
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
tooltipDateFormat: "EEE, MMM dd # h:mm:ss a"
}));
//x-axis dash lines
var xRenderer = xAxis.get("renderer");
xRenderer.grid.template.setAll({
strokeDasharray: [6],
});
//series
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
xAxis: xAxis,
yAxis: yAxis,
openValueXField: "Start",
valueXField: "End",
categoryYField: "State",
sequencedInterpolation: true,
tooltip: am5.Tooltip.new(root, {
//labelText: "[bold {Color} fontSize: 16px]{State}[/]\n[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
labelText: "[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
getFillFromSprite: false
})
}));
series.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
tooltipText: "{State}:\n[bold]{openValueX}[/] - [bold]{valueX}[/]"
});
series.columns.template.adapters.add("fill", function (text, target, key) {
//console.log(target);
//have to check for empty
//if(target.dataItem) {
if(target.dataItem.dataContext.State == "Active") {
return am5.color("#7bc07b"); //active
} else {
return am5.color("#55bfe6"); //idle
}
//} else {
// return null;
//}
});
//series
var series2 = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Clicks",
fill: am5.color("#679fd0"),
xAxis: xAxis,
yAxis: yAxis2,
valueYField: "Clicks",
valueXField: "Timestamp",
tooltip: am5.Tooltip.new(root, {
labelText: "{valueY}",
getFillFromSprite: false
})
}));
series2.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series2.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
});
series2.get("tooltip").label.adapters.add("text", function (text, target, key) {
//console.log(target);
//have to check for empty
if(target.dataItem) {
return "Total : [bold]{Clicks}[/]\nTimestamp : [bold]{Timestamp}[/]";
} else {
return null;
}
});
//title
var title = chart.children.unshift(am5.Label.new(root, {
fontSize: 12,
textAlign: "left",
x: am5.percent(0),
y: am5.percent(0),
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
text: "some label"
}));
//cursor
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
snapToSeries: [ series ],
snapToSeriesBy: "x",
behavior: "zoomX"
}));
cursor.lineX.set("visible", false);
cursor.lineY.set("visible", false);
//formatting
series.data.processor = am5.DataProcessor.new(root, {
dateFields: ["Start", "End"],
dateFormat: "xxxxxxxxxxxxx"
});
//formatting
series2.data.processor = am5.DataProcessor.new(root, {
numericFields: ["Clicks"],
dateFields: ["Timestamp"],
dateFormat: "xxxxxxxxxxxxx"
});
//scrollbar
chart.set("scrollbarX", am5.Scrollbar.new(root, {
orientation: "horizontal",
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
}));
//exporting
exporting = am5plugins_exporting.Exporting.new(root, {
dataSource: data,
dataFields: {
State: 'State', Start: 'Start', End: 'End', Duration: 'Duration'
},
dateFields: ["Start", "End"],
dateFormat: "MM/dd/yyyy hh:mm:ss a",
durationFields: ["Duration"],
durationFormat: "hh'h' mm'm' ss's'",
filePrefix: 'User Activity'
});
//add data
series.data.setAll(data);
series2.data.setAll(mousekeys);
//make stuff animate on load
series.appear(1000);
series2.appear(1000);
chart.appear(1000, 100);

yAxis and yAxis2 are not stacked. You have to be more explicit and add this line of code:
chart.leftAxesContainer.set("layout", root.verticalLayout);
If you want to place your column chart above, you need to push yAxis2 before yAxis or use unshift():
var yAxis2 = chart.yAxes.unshift(am5xy.ValueAxis.new(root, {
// ...
}));
I put your code below with these two little modifications:
// Set data
var data = [{
"State": "Idle",
"Start": 1424321864000,
"End": 1424321875000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424322649000,
"End": 1424322669000,
"Duration": 20
}, {
"State": "Idle",
"Start": 1424322970000,
"End": 1424322981000,
"Duration": 11
}, {
"State": "Idle",
"Start": 1424323093000,
"End": 1424323139000,
"Duration": 46
}, {
"State": "Active",
"Start": 1424323250000,
"End": 1424323268000,
"Duration": 18
}, {
"State": "Idle",
"Start": 1424323680000,
"End": 1424323703000,
"Duration": 23
}];
var mousekeys = [{
"Timestamp": 1424318400000,
"Clicks": "20",
"Keypresses": "30"
}];
/**
* ---------------------------------------
* This demo was created using amCharts 5.
*
* For more information visit:
* https://www.amcharts.com/
*
* Documentation is available at:
* https://www.amcharts.com/docs/v5/
* ---------------------------------------
*/
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
//font size theme
var myTheme = am5.Theme.new(root);
myTheme.rule("Label").setAll({
fontSize: 12
});
root.setThemes([
am5themes_Animated.new(root),
myTheme
]);
root.locale = am5locales_en_US;
//chartReg['chart'].utc = true; //force chart to show in UTC instead of device timezone
root.timezone = am5.Timezone.new('UTC'); //user timezone
//duration format
root.durationFormatter.setAll({
baseUnit: "second",
durationFormat: "hh'h' mm'm' ss's'"
});
//create chart
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: false,
wheelY: false,
layout: root.verticalLayout,
marginTop: 0,
marginRight: 0,
marginBottom: 0,
marginLeft: 0,
paddingTop: 0,
paddingRight: 20,
paddingBottom: 20,
paddingLeft: 10,
}));
chart.leftAxesContainer.set("layout", root.verticalLayout); // <--- HERE
//zoom button
//chart.zoomOutButton.setAll({
// forceHidden: true, //disables zoom button
//});
chart.zoomOutButton.get("background").setAll({
fill: am5.color("#BDBDBD"),
});
chart.zoomOutButton.get("background").states.create("hover", {}).setAll({
fill: am5.color("#8a8a8a"),
});
chart.zoomOutButton.get("background").states.create("down", {}).setAll({
fill: am5.color("#707070"),
});
chart.zoomOutButton.get("background").states.create("active", {}).setAll({
fill: am5.color("#707070"),
});
//create axes
var yAxis = chart.yAxes.push(am5xy.CategoryAxis.new(root, {
text: "State",
fontWeight: "500",
height: am5.percent(70),
categoryField: "State",
renderer: am5xy.AxisRendererY.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
}));
var yAxis2 = chart.yAxes.unshift(am5xy.ValueAxis.new(root, { // <--- HERE
text: "Clicks",
fontWeight: "500",
height: am5.percent(30),
min: 0, //min 'hint', but not forced
//strictMinMax: true, //forces the min/max
//extraMax: 0.1, //extra 10% to the value range which acts as 'padding' to the yaxis
renderer: am5xy.AxisRendererY.new(root, {})
}));
//the order is top to bottom ends up bottom to top on the chart
yAxis.data.setAll([
{ State: "Idle" },
{ State: "Active" }
]);
//y-axis dash lines
var yRenderer = yAxis.get("renderer");
yRenderer.grid.template.setAll({
strokeDasharray: [6]
});
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
tooltip: am5.Tooltip.new(root, {}),
tooltipDateFormat: "EEE, MMM dd # h:mm:ss a"
}));
//x-axis dash lines
var xRenderer = xAxis.get("renderer");
xRenderer.grid.template.setAll({
strokeDasharray: [6],
});
//series
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
xAxis: xAxis,
yAxis: yAxis,
openValueXField: "Start",
valueXField: "End",
categoryYField: "State",
sequencedInterpolation: true,
tooltip: am5.Tooltip.new(root, {
//labelText: "[bold {Color} fontSize: 16px]{State}[/]\n[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
labelText: "[bold]Start :[/] {openValueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]End :[/] {valueX.formatDate(\"EEE',' MM'/'dd'/'yyyy '#' h':'mm':'ss a\")}\n[bold]Duration :[/] {Duration.formatDuration(\"hh'h' mm'm' ss's'\")}",
getFillFromSprite: false
})
}));
series.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
tooltipText: "{State}:\n[bold]{openValueX}[/] - [bold]{valueX}[/]"
});
series.columns.template.adapters.add("fill", function (text, target, key) {
//console.log(target);
//have to check for empty
//if(target.dataItem) {
if(target.dataItem.dataContext.State == "Active") {
return am5.color("#7bc07b"); //active
} else {
return am5.color("#55bfe6"); //idle
}
//} else {
// return null;
//}
});
//series
var series2 = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Clicks",
fill: am5.color("#679fd0"),
xAxis: xAxis,
yAxis: yAxis2,
valueYField: "Clicks",
valueXField: "Timestamp",
tooltip: am5.Tooltip.new(root, {
labelText: "{valueY}",
getFillFromSprite: false
})
}));
series2.get("tooltip").get("background").setAll({
fill: am5.color("#ffffff"),
fillOpacity: 1,
strokeWidth: 2,
stroke: am5.color("#bbbbbb"),
});
//series columns
series2.columns.template.setAll({
fillOpacity: 1,
stroke: 0,
strokeWidth: 0, //doesn't seem to work use 'stroke:0'
});
series2.get("tooltip").label.adapters.add("text", function (text, target, key) {
//console.log(target);
//have to check for empty
if(target.dataItem) {
return "Total : [bold]{Clicks}[/]\nTimestamp : [bold]{Timestamp}[/]";
} else {
return null;
}
});
//title
var title = chart.children.unshift(am5.Label.new(root, {
fontSize: 12,
textAlign: "left",
x: am5.percent(0),
y: am5.percent(0),
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
text: "some label"
}));
//cursor
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
snapToSeries: [ series ],
snapToSeriesBy: "x",
behavior: "zoomX"
}));
cursor.lineX.set("visible", false);
cursor.lineY.set("visible", false);
//formatting
series.data.processor = am5.DataProcessor.new(root, {
dateFields: ["Start", "End"],
dateFormat: "xxxxxxxxxxxxx"
});
//formatting
series2.data.processor = am5.DataProcessor.new(root, {
numericFields: ["Clicks"],
dateFields: ["Timestamp"],
dateFormat: "xxxxxxxxxxxxx"
});
//scrollbar
chart.set("scrollbarX", am5.Scrollbar.new(root, {
orientation: "horizontal",
marginTop: 0,
marginRight: 0,
marginBottom: 30,
marginLeft: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
}));
//exporting
exporting = am5plugins_exporting.Exporting.new(root, {
dataSource: data,
dataFields: {
State: 'State', Start: 'Start', End: 'End', Duration: 'Duration'
},
dateFields: ["Start", "End"],
dateFormat: "MM/dd/yyyy hh:mm:ss a",
durationFields: ["Duration"],
durationFormat: "hh'h' mm'm' ss's'",
filePrefix: 'User Activity'
});
//add data
series.data.setAll(data);
series2.data.setAll(mousekeys);
//make stuff animate on load
series.appear(1000);
series2.appear(1000);
chart.appear(1000, 100);
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
#chartdiv {
width: 100%;
height: 500px;
}
<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>
<script src="https://cdn.amcharts.com/lib/5/locales/en_US.js"></script>
<script src="https://cdn.amcharts.com/lib/5/plugins/exporting.js"></script>
<div id="chartdiv"></div>
You can see a column if you use the horizontal scrollbar and go completely to the left. The reason is there:
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "second", count: 1 },
// ...
}));
Your interval is tiny (one second), so your column width is tiny. You have to tweak timeUnit or count in baseInterval if you want a wider column.

Related

Amcharts 5 Separate Label into points with the same date

I use AmCharts 5 and sometimes the data can come with a different value but with the same date
Result example:
[
{"result":"AAA","date":"2022-06-09T23:00:00","value":155},
{"result":"BBB","date":"2022-06-10T07:00:00","value":25},
{"result":"CCC","date":"2022-06-11T07:00:00","value":85},
{"result":"DDD","date":"2022-06-12T07:00:00","value":65},
{"result":"EEE","date":"2022-06-12T08:00:00","value":198},
]
But when there is more than one record on the same date, it shows the points, but there is an equal Label for all points.
My code is:
https://jsfiddle.net/sNniffer/9xk6q3eu/17/
I need each point to have its Label, even if they are on the same date
In your example, date strings are all unique!
The easiest solution here is to use hour as timeUnit in the settings of your DateAxis.
am5.ready(function() {
var root = am5.Root.new("chartdiv");
var chart = root.container.children.push(am5xy.XYChart.new(root, {}));
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: {
timeUnit: "hour", // Put "hour" instead of "day"
count: 1
},
renderer: am5xy.AxisRendererX.new(root, {}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis
}));
cursor.lineY.set("visible", false);
var series = chart.series.push(am5xy.SmoothedXLineSeries.new(root, {
name: "Series",
xAxis: xAxis,
yAxis: yAxis,
categoryXField: "result",
valueXField: "date",
valueYField: "value",
tooltip: am5.Tooltip.new(root, {
labelText: "[bold]Result:[/] {categoryX}\n[bold]Date:[/] {valueX.formatDate()}\n[bold]Value:[/] {valueY}"
})
}));
series.fills.template.setAll({
visible: true,
fillOpacity: 0.2
});
series.bullets.push(function() {
return am5.Bullet.new(root, {
sprite: am5.Circle.new(root, {
radius: 8,
stroke: root.interfaceColors.get("background"),
strokeWidth: 2,
interactive: false,
fill: series.get("fill")
})
});
});
var data = [
{result: "AAA", date: new Date("2022-06-09T23:00:00").getTime(), value: 155},
{result: "BBB", date: new Date("2022-06-10T07:00:00").getTime(), value: 25},
{result: "CCC", date: new Date("2022-06-11T07:00:00").getTime(), value: 85},
{result: "DDD", date: new Date("2022-06-12T07:00:00").getTime(), value: 65},
{result: "EEE", date: new Date("2022-06-12T08:00:00").getTime(), value: 198}
];
series.data.setAll(data);
});
#chartdiv {
width: 100%;
height: 350px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<div id="chartdiv"></div>

How to create gauge diagram with amchart 5 with arabic text in it

I want to create a gauge diagram with amcharts 5 with persian text on it. All the code sample I found is working correctly with english text on it. But when I want to use persian or arabic text (rtl languages), it doesn't show texts correct. How can I solve this problem?
Here is my code:
<script>
var root = am5.Root.new("chartdiv");
root.setThemes([
am5themes_Animated.new(root)
]);
var chart = root.container.children.push(am5radar.RadarChart.new(root, {
panX: false,
panY: false,
startAngle: 160,
endAngle: 380
}));
var axisRenderer = am5radar.AxisRendererCircular.new(root, {
innerRadius: -40
});
axisRenderer.grid.template.setAll({
stroke: root.interfaceColors.get("background"),
visible: true,
strokeOpacity: 0.8
});
var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation: 0,
min: -40,
max: 100,
strictMinMax: true,
renderer: axisRenderer
}));
var axisDataItem = xAxis.makeDataItem({});
var clockHand = am5radar.ClockHand.new(root, {
pinRadius: am5.percent(20),
radius: am5.percent(100),
bottomWidth: 40
})
var bullet = axisDataItem.set("bullet", am5xy.AxisBullet.new(root, {
sprite: clockHand
}));
xAxis.createAxisRange(axisDataItem);
var label = chart.radarContainer.children.push(am5.Label.new(root, {
fill: am5.color(0xffffff),
centerX: am5.percent(50),
textAlign: "center",
centerY: am5.percent(50),
fontSize: "3em"
}));
axisDataItem.set("value", 50);
bullet.get("sprite").on("rotation", function () {
var value = axisDataItem.get("value");
var text = Math.round(axisDataItem.get("value")).toString();
var fill = am5.color(0x000000);
xAxis.axisRanges.each(function (axisRange) {
if (value >= axisRange.get("value") && value <= axisRange.get("endValue")) {
fill = axisRange.get("axisFill").get("fill");
}
})
label.set("text", Math.round(value).toString());
clockHand.pin.animate({ key: "fill", to: fill, duration: 500, easing: am5.ease.out(am5.ease.cubic) })
clockHand.hand.animate({ key: "fill", to: fill, duration: 500, easing: am5.ease.out(am5.ease.cubic) })
});
var i = 0;
var a = setInterval(function() {
if (i === 9) {
axisDataItem.animate({
key: "value",
to: Math.round(28),
duration: 100,
easing: am5.ease.out(am5.ease.cubic)
});
}
else if (i === 25) {
clearInterval(a);
}
else {
axisDataItem.animate({
key: "value",
to: Math.round(Math.random() * 140 - 40),
duration: 2000,
easing: am5.ease.out(am5.ease.cubic)
});
i++;
}
}
, 100);
var bandsData = [{
title: "لاغری مفرط",
direction: "rtl",
position: "right",
orientation: "rtl",
color: "#ee1f25",
lowScore: -40,
highScore: -20
}, {
title: 'لاغر',
color: "#f04922",
lowScore: -20,
highScore: 0
}, {
title: "نرمال",
color: "#fdae19",
lowScore: 0,
highScore: 20
}, {
title: "اضافه وزن",
color: "#f3eb0c",
lowScore: 20,
highScore: 40
}, {
title: "چاق",
color: "#b0d136",
lowScore: 40,
highScore: 60
}, {
title: "چاقی زیاد",
color: "#54b947",
lowScore: 60,
highScore: 80
}, {
title: "چاقی مفرط",
color: "#0f9747",
lowScore: 80,
highScore: 100
}];
am5.array.each(bandsData, function (data) {
var axisRange = xAxis.createAxisRange(xAxis.makeDataItem({}));
axisRange.setAll({
value: data.lowScore,
endValue: data.highScore
});
axisRange.get("axisFill").setAll({
visible: true,
fill: am5.color(data.color),
fillOpacity: 0.8
});
axisRange.get("label").setAll({
text: data.title,
inside: true,
radius: 15,
fontSize: "0.9em",
fill: root.interfaceColors.get("background")
});
});
chart.rtl = true;
chart.appear(1000, 100);
chart.rtl = true;
</script>
Final result is like this image:
amcharts5 result
I also searched about it in documentation of amcharts 5 but I couldn't find the answer.

How to pass data in Laravel with Chart.js

I want to display total of men and woman from learnings table in chart using Chartjs in Laravel.
My controller
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
$learning = $men_learning + $women_learning ;
return view('home', compact('learning'));
}
My script in blade view.
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['total'],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
How can I propagate loaded statistic from my script to the chart?
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
return view('home', compact('men_learning', 'women_learning'));
}
<script type="text/javascript">
$(function(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Men', 'Women'],
datasets: [{
label: 'Men',
data: [{!!$men_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(40,167,69,1)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0 ,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(254,86,83,.8)',
},
{
label: 'Women',
data: [{!!$women_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(220,53,69,.8)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(63,82,227,.8)',
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
display: true,
drawBorder: false,
color: '#f2f2f2',
},
ticks: {
beginAtZero: true,
stepSize: 100,
callback: function(value, index, values) {
return value;
}
}
}],
xAxes: [{
gridLines: {
display: false,
tickMarkLength: 15,
}
}]
},
}
});
});
</script>

How do I set the style for the legend data differently per dataset with Chart.js?

I have created a chart with Chart.js, and I now need to show the data in the legend differently per the two different datasets.
How do I show the first dataset 'Low/High Range Limit' in the classic rectangle/fill style and the dataset 'Patient Results' in the point style?
(Bonus: Currently, I'm showing the second dataset near-correctly. I also want to completely fill the circle with the solid 'steelblue' color, not with transparency.)
(I would provide an image but I need at least 10 reputation to post them.)
<style>
.chart-container { width: 550px }
</style>
<div class="chart-container">
<canvas id="myChart" width="2" height="1"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script>
var context = document.getElementById('myChart');
var myChart = new Chart(context, {
type: 'line',
data: {
labels: ['(A)', '(B)', '(C)', '(D)'],
datasets: [
{
label: 'Patient Results',
data: [40, 230, 30, 60],
borderColor: 'steelblue',
borderWidth: 2,
pointBackgroundColor: 'steelblue',
fill: false,
spanGaps: true // if true, lines will be drawn between points with no or null data. if false, points with NaN data will create a break in the line.
},
{
data: [0, 30, 20, 20], // representing the low range only
borderColor: '#222',
borderWidth: 2,
pointRadius: 0,
fill: true,
backgroundColor: '#fff'
},
{
label: 'Low/High Range Limit',
data: [60, 150, 50, 40], // representing the high range only
borderColor: '#222',
borderWidth: 2,
pointRadius: 0,
fill: true,
backgroundColor: '#c2e8f5'
}
]
},
options: {
elements: {
line: {
tension: 0 // disables bezier curves
}
},
legend: {
labels: {
boxWidth: 6,
filter: function(legendItem, chartData) {
if (legendItem.datasetIndex === 1) {
return false;
}
return true;
},
usePointStyle: true
},
position: 'right',
reverse: true // shows 'Low/High Range Limit' first
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

canvasJS x axis change between different screen

I use canvasJS to paint chart,but when the page change different window, the X axis will show different. when page open in little window show right like this enter image description here,but when page show big window show wrong like thisenter image description here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: false,
animationEnabled: false,
title: {
text: "BJS Site Record Item QTY"
},
axisY2: {
valueFormatString: "0",
maximum: 50,
interval: 5,
interlacedColor: "#F5F5F5",
gridColor: "#D7D7D7",
tickColor: "#D7D7D7"
},
axisX:{
//title: "BJS Site Record Item QTY",
interval: 1
},
theme: "theme2",
toolTip: {
shared: true
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 15,
fontFamily: "Lucida Sans Unicode"
},
data: [
{
type: "line",
lineThickness: 3,
axisYType: "secondary",
showInLegend: true,
name: "BJSC",
dataPoints: [
{ x: new Date(2016,11,08), y:11 },
{ x: new Date(2016,11,09), y:0 },
{ x: new Date(2016,11,10), y:0 },
{ x: new Date(2016,11,11), y:0 },
{ x: new Date(2016,11,12), y:0 },
{ x: new Date(2016,11,13), y:0 },
{ x: new Date(2016,11,14), y:0 },
]
},
],
legend: {
cursor: "pointer",
itemclick: function (e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
</script>
Scott,
intervalType defaults to “number” when you set the interval. If you prefer interval to be 1 day, set intervalType to "day" along with setting interval to 1.
Check this code.
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: false,
animationEnabled: false,
title: {
text: "BJS Site Record Item QTY"
},
axisY2: {
valueFormatString: "0",
maximum: 50,
interval: 5,
interlacedColor: "#F5F5F5",
gridColor: "#D7D7D7",
tickColor: "#D7D7D7"
},
axisX: {
//title: "BJS Site Record Item QTY",
interval: 1,
intervalType: "day"
},
theme: "theme2",
toolTip: {
shared: true
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 15,
fontFamily: "Lucida Sans Unicode"
},
data: [
{
type: "line",
lineThickness: 3,
axisYType: "secondary",
showInLegend: true,
name: "BJSC",
dataPoints: [
{ x: new Date(2016, 11, 08), y: 11 },
{ x: new Date(2016, 11, 09), y: 0 },
{ x: new Date(2016, 11, 10), y: 0 },
{ x: new Date(2016, 11, 11), y: 0 },
{ x: new Date(2016, 11, 12), y: 0 },
{ x: new Date(2016, 11, 13), y: 0 },
{ x: new Date(2016, 11, 14), y: 0 }
]
},
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 250px; width: 100%;"></div>

Resources