Amcharts visualize portion of data in horizontal bar chart - javascript

I'm trying to visualize an horizontal bar chart and I want to show just a portion of the loaded records and to be able to scroll the results.
I tried to perform this using a vertical scrollbar. This is the resulting JSFiddle: jsfiddle.
function loadBar(){
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Set up data source
chart.data= [
{"name": "Mario12","overhead": 2},
{"name": "Jenny12","overhead": 2},
...
];
//create category axis for years
var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
var yTitle = 'Agents';
categoryAxis.title.text = yTitle;
...
//create value axis for income and expenses
var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());
valueAxis.min = 0;
...
//create columns
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.categoryY = "name";
series.dataFields.valueX = "overhead";
...
chart.scrollbarY = new am4core.Scrollbar();
chart.scrollbarY.parent = chart.leftAxesContainer;
}
loadBar();
The wanted result should be instead result

Related

Amcharts - radar chart for one and two data items (amcharts4)

I am trying to display hexagon or octagon shape like radar series axis in case when I have only one or two items in data. Right Now it renders like that.
Following is my code snippet. I have looked at adapters for radar chart. So far, nothing useful found.
https://www.amcharts.com/docs/v4/reference/radarchart/#Adapters
Upon debugging, I found that series.pixelHeight is 0. Can you guys give some pointers. or show me the way?
const chart = am4core.create('al-radial-chart', am4charts.RadarChart)
chart.logo.disabled = true
chart.data = data
chart.radius = am4core.percent(70)
//* Create axes */
const categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis())
const valueAxis = chart.yAxes.push(new am4charts.ValueAxis())
// Fields
categoryAxis.dataFields.category = 'title'
valueAxis.title.fontWeight = 'bold'
valueAxis.renderer.gridType = 'polygons'
// Labels
valueAxis.renderer.labels.template.disabled = true
categoryAxis.renderer.labels.template.fontSize = 12
categoryAxis.renderer.labels.template.fill = am4core.color(colors.text)
// Axes
categoryAxis.renderer.grid.template.strokeWidth = 2
categoryAxis.renderer.grid.template.strokeOpacity = 0.99
categoryAxis.renderer.grid.template.fillOpacity = 0.05
categoryAxis.renderer.labels.template.html = `
<div style="width: ${
window.innerWidth < 1000 ? 80 : window.innerWidth < 1500 ? 120 : 150
}px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; text-align: center;">{category}</div>
<div style="text-align: center; font-weight: bold">{score.formatNumber("#,###.0")}</div>`
categoryAxis.renderer.labels.template.tooltipText = `[bold]{title}[/]\n score is [bold]{score.formatNumber("#,###.0")}[/]`
categoryAxis.tooltip.getFillFromObject = false
categoryAxis.tooltip.background.fill = am4core.color(colors.turq)
categoryAxis.tooltip.background.stroke = am4core.color(colors.turq)
categoryAxis.renderer.grid.template.fill = am4core.color(colors.gridFill)
categoryAxis.renderer.grid.template.stroke = am4core.color(colors.lines)
valueAxis.renderer.grid.template.strokeWidth = 2
valueAxis.renderer.grid.template.strokeOpacity = 0.99
valueAxis.renderer.grid.template.fillOpacity = 0.05
valueAxis.renderer.grid.template.fill = am4core.color(colors.gridFill)
valueAxis.renderer.grid.template.stroke = am4core.color(colors.lines)
valueAxis.zIndex = 1
categoryAxis.zIndex = 2
/* Create and configure series */
const series = chart.series.push(new am4charts.RadarSeries())
// series.zIndex = 1
series.dataFields.valueY = 'score'
series.dataFields.categoryX = 'title'
series.strokeWidth = 2
series.stroke = am4core.color(colors.turq)
series.fillOpacity = 0.4
series.sequencedInterpolation = true
series.sequencedInterpolationDelay = 100
I have created dummy data with valueAxis values set to zero and with different titles. Have used the categoryAxis htmlOutput adapter to hide those labels. Because my values were zero chart rendered correctly. Will post a code solution to this problem shortly.

Rounded Edge Stacked Grouped Chart in amchart4

I've been looking everywhere but still can't find the answer, i have stacked and clustered chart on my website (Using amchart4), like this :
Screenshot for chart in my website
, what i want to is, round the edge of the top the chart, so chart can look like this :
Chart that have rounded corner
, I've been trying to add an adapter, base on documentation in amchart4 : https://www.amcharts.com/docs/v4/tutorials/stacked-column-series-with-rounded-corners/
but instead working like a charm, my chart look like this :
My chart Now!
where's my mistake here?
My Js Code for amchart :
am4core.ready(function() {
// Create chart instance
var chart = am4core.create('regional', am4charts.XYChart);
// Add data
chart.data = response.data;
// Create axes
var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.renderer.grid.template.disabled = true;
categoryAxis.dataFields.category = "regional";
// Room for sub-category labels
categoryAxis.renderer.labels.template.marginTop = 20;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.min = 0;
// Create series
function createSeries(field, name, stacked, color) {
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueY = field;
series.dataFields.categoryX = "regional";
series.name = name;
series.stroke = am4core.color(color);
series.fill = am4core.color(color);
// series.columns.template.tooltipText = "{name}: [bold]{valueY}[/]";
series.stacked = stacked;
series.columns.template.column.adapter.add("cornerRadiusTopLeft", cornerRadius);
series.columns.template.column.adapter.add("cornerRadiusTopRight", cornerRadius);
var bullet1 = series.bullets.push(new am4charts.LabelBullet());
bullet1.interactionsEnabled = false;
bullet1.label.text = "{valueY}";
bullet1.label.fontSize = 19;
bullet1.label.fill = am4core.color("#0d0b0b");
bullet1.locationY = 0.5;
}
// Fake series (display cluster label)
function createLabelSeries(name) {
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueY = "zero";
series.dataFields.categoryX = "regional";
series.name = name;
series.hiddenInLegend = true;
var bullet = series.bullets.push(new am4charts.LabelBullet());
bullet.label.text = "{name}";
bullet.label.hideOversized = false;
bullet.label.paddingTop = 30;
}
// Corner
function cornerRadius(radius, item) {
var dataItem = item.dataItem;
// Find the last series in this stack
var lastSeries;
chart.series.each(function(series) {
if (dataItem.dataContext[series.dataFields.valueY] && !series.isHidden && !series.isHiding) {
lastSeries = series;
}
});
// console.log(lastSeries.name);
// If current series is the one, use rounded corner
return dataItem.component == lastSeries ? 10 : radius;
}
chart.maskBullets = false;
createLabelSeries("OPEN");
createSeries("NCR_OPEN", "NCR OPEN", true, "#ff955c");
createSeries("HCR_OPEN", "HCR OPEN", true, "#ff7429");
createSeries("PCR_OPEN", "PCR OPEN", true, "#fa4300");
createLabelSeries("CLOSE");
createSeries("NCR_CLOSE", "NCR CLOSE", true, "#8870ff");
createSeries("HCR_CLOSE", "HCR CLOSE", true, "#5d3dff");
createSeries("PCR_CLOSE", "PCR CLOSE", true, "#370fff");
// Legend
chart.legend = new am4charts.Legend();
})

Change font color of labels and title of a 3D bar chart drawn using amcharts

I have drawn a 3D stacked bar chart as follows.
$scope.DrawFunction = function()
{
am4core.useTheme(am4themes_animated);
// Themes end
// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart3D);
// Add data
chart.data = [{
"country": "USA",
"year2017": 3.5,
"year2018": 4.2
}, {
"country": "UK",
"year2017": 1.7,
"year2018": 3.1
}];
// Create axes
var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "country";
categoryAxis.renderer.grid.template.location = 0;
categoryAxis.renderer.minGridDistance = 30;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.title.text = "GDP growth rate";
valueAxis.renderer.labels.template.adapter.add("text", function(text) {
return text + "%";
});
// Create series
var series = chart.series.push(new am4charts.ColumnSeries3D());
series.dataFields.valueY = "year2017";
series.dataFields.categoryX = "country";
series.name = "Year 2017";
series.clustered = false;
series.columns.template.tooltipText = "[white]GDP grow in {category} (2017): [bold]{valueY}[/]";
series.columns.template.fillOpacity = 0.9;
var series2 = chart.series.push(new am4charts.ColumnSeries3D());
series2.dataFields.valueY = "year2018";
series2.dataFields.categoryX = "country";
series2.name = "Year 2018";
series2.clustered = false;
series2.columns.template.tooltipText = "GDP grow in {category} (2017): [bold]{valueY}[/]";
}
graph is generated correctly. I want to change the font color of all labels and the title into another color. I managed to change the font color of tootltip letters but couldn't find a way to change the font color of others.How can I do that ?
As I understand we can't change the font color of all the letters shown through out the graph unless we change the theme we have selected. So in my scenario since my background color is dark I wanted to change all the fonts within the graph to white. For that we need to import another theme rather than trying to change the font-color. you can download the dark theme from the following link
https://www.amcharts.com/lib/4/themes/dark.js
And import the library in your script as follows
<script src="https://www.amcharts.com/lib/4/themes/dark.js"></script>
Next along with animated.js theme call the dark theme as follows
am4core.useTheme(am4themes_dark);
am4core.useTheme(am4themes_animated);
Then all the fonts will become white in color and also the grid lines

Add HTML Element On Top Of Amchart Instance

I can't find this in the documentation, but is it possible to add a custom div element on top of an Amchart Instance?
Such that:
<div class="container-fluid px-0 mx-0">
<div id="chartdiv"></div>
<ul>
<li>Thailand</li>
<li>Myanmar</li>
<li>Etc...</li>
</ul>
</div>
With the UL displaying at the bottom of the instance?
JS:
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/maps.js"></script>
<script src="https://www.amcharts.com/lib/4/geodata/worldUltra.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<script>
am4core.useTheme(am4themes_animated);
var container = am4core.create("chartdiv", am4core.Container);
container.width = am4core.percent(100);
container.height = am4core.percent(100);
container.layout = "vertical";
// Create map instance
var chart = container.createChild(am4maps.MapChart);
// Set map definition
chart.geodata = am4geodata_worldUltra;
// Set projection
chart.projection = new am4maps.projections.Miller();
// Create map polygon series
var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());
// Exclude Antartica
polygonSeries.exclude = ["AQ"];
// Make map load polygon (like country names) data from GeoJSON
polygonSeries.useGeodata = true;
// Configure series
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#dcdcdc");
// Create hover state and set alternative fill color
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#a98239");
chart.events.on("ready", function(ev) {
chart.zoomToMapObject(polygonSeries.getPolygonById("TH"));
});
chart.zoomControl = new am4maps.ZoomControl();
chart.chartContainer.wheelable = false;
</script>
If I missed something in the docs, I apologize - hoping someone can point me in the right direction!
AmCharts is SVG based so everything in the chartdiv is controlled by the library and mostly contains SVG with a little bit of HTML, without any native options to include custom div objects. One potential workaround is to use a Label object and set its html property to include your HTML code. Note that this uses <foreignObject> to accomplish this, so you may need to be mindful of browser support (IE11, if that still matters).
Here's an example that creates a list on top of the chart
var label = chart.chartContainer.createChild(am4core.Label);
//label.isMeasured = false; //uncomment to make the label not adjust the rest of the chart elements to accommodate its placement
label.fontSize = 16;
label.x = am4core.percent(5);
label.horizontalCenter = "middle";
label.verticalCenter = "bottom";
label.html = "<ul><li>List item 1</li><li>List item 2</li></ul>";
label.toBack(); //move list to top of the chart area. See: https://www.amcharts.com/docs/v4/concepts/svg-engine/containers/#Ordering_elements
Demo:
// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Add data
chart.data = [{
"category": "Research",
"value": 450
}, {
"category": "Marketing",
"value": 1200
}, {
"category": "Distribution",
"value": 1850
}];
// Create axes
var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "category";
categoryAxis.renderer.grid.template.location = 0;
//categoryAxis.renderer.minGridDistance = 30;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueY = "value";
series.dataFields.categoryX = "category";
var label = chart.chartContainer.createChild(am4core.Label);
//label.isMeasured = false; //uncomment to make the label not adjust the rest of the chart elements to accommodate its placement
label.fontSize = 16;
label.x = am4core.percent(5);
label.horizontalCenter = "middle";
label.verticalCenter = "bottom";
label.html = "<ul><li>List item 1</li><li>List item 2</li></ul>";
label.toBack(); //move list to top of the chart area. See: https://www.amcharts.com/docs/v4/concepts/svg-engine/containers/#Ordering_elements
html, body { width: 100%; height: 100%; margin: 0;}
#chartdiv { width: 100%; height: 100%;}
<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv"></div>

Amchart - Export to PNG file

I created an amchart for plotting time based area. I need to add an export to image option to this graph. Below shows my amchart code. What are the lines needed to add the export to image option to this graph
AmCharts.ready(function () {
// first we generate some random data
generateChartData();
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "../amcharts/images/";
chart.dataProvider = chartData;
chart.categoryField = "date";
// data updated event will be fired when chart is first displayed,
// also when data will be updated. We'll use it to set some
// initial zoom
chart.addListener("dataUpdated", zoomChart);
// AXES
// Category
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true; // in order char to understand dates, we should set parseDates to true
categoryAxis.minPeriod = "mm"; // as we have data with minute interval, we have to set "mm" here.
categoryAxis.gridAlpha = 0.07;
categoryAxis.axisColor = "#DADADA";
// Value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.gridAlpha = 0.07;
valueAxis.title = "Unique visitors";
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.type = "line"; // try to change it to "column"
graph.title = "red line";
graph.valueField = "visits";
graph.lineAlpha = 1;
graph.lineColor = "#d1cf2a";
graph.fillAlphas = 0.3; // setting fillAlphas to > 0 value makes it area graph
chart.addGraph(graph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorPosition = "mouse";
chartCursor.categoryBalloonDateFormat = "JJ:NN, DD MMMM";
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chart.addChartScrollbar(chartScrollbar);
// WRITE
chart.write("chartdiv");
});
You should just be able to add the following before you write the chart to the DIV.
"exportConfig":{
"menuTop": 0,
menuItems: [{
textAlign: 'center',
icon: 'images/graph_export.png',
iconTitle: 'Save chart as an image',
onclick:function(){},
items: [
{title:'JPG', format:'jpg'},
{title:'PNG', format:'png'},
{title:'SVG', format:'svg'}
]
}]
}
This will give you a download icon on the graph to download in either JPG, PNG or SVG formats.
Try this code :
chart.export = {
enabled: true,
position: "bottom-right"
}
chart.initHC = false;
chart.validateNow();
And don't forget to include the needed export plugin!

Categories