How can I show a legend entry for every column in Amcharts?

Take a look at this code snippet: http://jsfiddle.net/ouLed1fp/

How can I create a legend entry for each column in the chart? Also, is there a way to display the column names next to them, providing a clear legend?

<div id="chartdiv" style="width: 100%; height: 355px;"></div>
<script>

var chart;

var chartData = [{
    country: "USA",
    visits: 4025,
    subdata: [
        { country: "New York", visits: 1000 },
        { country: "California", visits: 785 },
        { country: "Florida", visits: 501 },
        { country: "Illinois", visits: 321 },
        { country: "Washington", visits: 101 }
    ]},
{
    country: "China",
    visits: 1882},
{
    country: "Japan",
    visits: 1809},
{
    country: "Germany",
    visits: 1322}];

AmCharts.ready(function() {
    // SERIAL CHART
    chart = new AmCharts.AmSerialChart();
    chart.dataProvider = chartData;
    chart.categoryField = "country";
    chart.startDuration = 1;

    // AXES
    // category
    var categoryAxis = chart.categoryAxis;
    categoryAxis.labelRotation = 90;
    categoryAxis.gridPosition = "start";

    // value
    // in case you don't want to change default settings of value axis,
    // you don't need to create it, as one value axis is created automatically.
    // GRAPH
    var graph = new AmCharts.AmGraph();
    graph.valueField = "visits";
    graph.balloonText = "[[category]]: [[value]]";
    graph.type = "column";
    graph.lineAlpha = 0;
    graph.fillAlphas = 0.8;
    chart.addGraph(graph);

    chart.addListener("clickGraphItem", function (event) {
        // check if the clicked graph item has any subdata to drill-down into
        if (event.item.dataContext.subdata != undefined) {
            event.chart.dataProvider = event.item.dataContext.subdata;
            event.chart.validateData();
        }
    });

    var legend = new AmCharts.AmLegend();
    chart.addLegend(legend, "legenddiv");

    chart.write("chartdiv");
});

</script>

Answer №1

Success achieved by implementing the following solution:

/*
  This script generates legend markers for each category with respective colors.
*/
AmCharts.addInitHandler(function(chart) {
  // Verify if legend is enabled and custom generateFromData property is set
  if (!chart.legend || !chart.legend.enabled || !chart.legend.generateFromData) {
    return;
  }

  var categoryField = chart.categoryField;
  var colorField = chart.graphs[0].lineColorField || chart.graphs[0].fillColorsField;
  var legendData =  chart.dataProvider.map(function(data) {
    var markerData = {
      "title": data[categoryField] + ": " + data[chart.graphs[0].valueField], 
      "color": data[colorField]
    };
    if (!markerData.color) {
      markerData.color = chart.graphs[0].lineColor;
    }
    return markerData;
  });

  chart.legend.data = legendData;

}, ["serial"]);

var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "marginRight": 70,
  "legend": { 
    "generateFromData": true //custom property for the plugin
  },
  // Data Provider
  "dataProvider": [{
    "country": "USA",
    "visits": 3025,
    "color": "#FF0F00"
  }, {
    "country": "China",
    "visits": 1882,
    "color": "#FF6600"
  }, {
    "country": "Japan",
    "visits": 1809,
    "color": "#FF9E01"
  }, {
    "country": "Germany",
    "visits": 1322,
    "color": "#FCD202"
  }, {
    "country": "UK",
    "visits": 1122,
    "color": "#F8FF01"
  }, {
    "country": "France",
    "visits": 1114,
    "color": "#B0DE09"
  }, {
    "country": "India",
    "visits": 984,
    "color": "#04D215"
  }, {
    "country": "Spain",
    "visits": 711,
    "color": "#0D8ECF"
  }, {
    "country": "Netherlands",
    "visits": 665,
    "color": "#0D52D1"
  }, {
    "country": "Russia",
    "visits": 580,
    "color": "#2A0CD0"
  }, {
    "country": "South Korea",
    "visits": 443,
    "color": "#8A0CCF"
  }, {
    "country": "Canada",
    "visits": 441,
    "color": "#CD0D74"
  }],
  "valueAxes": [{
    "axisAlpha": 0,
    "position": "left",
    "title": "Visitors from country"
  }],
  "startDuration": 1,
  "graphs": [{
    "balloonText": "<b>[[category]]: [[value]]</b>",
    "fillColorsField": "color",
    "fillAlphas": 0.9,
    "lineAlpha": 0.2,
    "type": "column",
    "valueField": "visits"
  }],
  "chartCursor": {
    "categoryBalloonEnabled": false,
    "cursorAlpha": 0,
    "zoomable": false
  },
  "categoryField": "country",
  "categoryAxis": {
    "gridPosition": "start",
    "labelRotation": 45
  },
  "export": {
    "enabled": true
  }

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Seems like JavaScript's .active functionality is failing to function properly in my case

I'm encountering an issue with my website's homepage. I have a list of services displayed, and the intention is for a description to appear when one of the services is clicked. However, clicking on the buttons does not trigger the expected action ...

What steps can I take to improve my routing structure in nodejs and express?

My current WebAPI code is pretty modular, but I want to make it even more so. Right now, all the routes are in my server.js file and I would like to separate them into individual controllers. Any suggestions on how to achieve that? Here's an example: ...

Tips for utilizing a button within a hyperlink in a React component:

I am new to react and have been working on the following code: import {NavLink as Link} from 'react-router-dom' return ( <div> {posts.map((actualData, index) => ( <Link to={'/' + actualData.id}> <d ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

Encountering a three.js issue while generating a large number of point lights

//////twinkling stars for (let index = 0; index < 1000; index++) { const stargeometry = new THREE.SphereGeometry(1, 24, 24); //create star sphere size const starmaterial = new THREE.MeshStandardMaterial({ color: 0xffffff }); //define star textur ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

How do I determine the appropriate image type to use?

I'm a beginner in the world of Node.js and I'm currently working on an application that stores image files. However, I am unsure about what type of data the images should be. const userSchema = new mongoose.Schema({ userImage: { type ...

Utilizing React Material-Table to Trigger a React Component through Table Actions

I have set up a datatable using the code below. <MaterialTable icons={tableIcons} title={title} columns={columns} data={data} actions={[ { icon: () => <Edit />, t ...

What is the function of '@' symbol in coding?... obtain {ModuleName} from '@ModuleName'

What is the significance of the '@' symbol in imports? I've noticed that various modules like '@react-navigation', '@babel', and others use the '@' symbol. Does this symbol serve a specific purpose, or is it s ...

Include image hover text without using HTML

I am looking to add a hover effect to some images using CSS and JS since I cannot directly edit the HTML file. The goal is to have centered text pop out when hovering over certain images. I know the div class of the image but unfortunately, I cannot add te ...

Steps for displaying the output of a post request in printing

I am currently working on creating a basic search bar functionality for daycares based on user input. I am utilizing a post request to an API and receiving back a list of daycares that match the input. Below is the code snippet: <template> <div ...

Obtain a collection of strings from an array of objects based on specified criteria

What is the most efficient method to extract an array of specific strings from an array of objects, where a certain condition needs to be met? Solution Attempt: const array = [{ "Item": "A", "Quantity": 2 ...

Switch out a specific string within a JavaScript object

{ 1:' {person} experimenting for 1 ', 2:'{person} experimenting for 2 ', 3:'{person} experimenting for 3 ', 4:'{person} experimenting for 4 ', 5:'{person} experimenting for 5 ' } Imag ...

"How to change the hover background of a select element in Chrome from its default setting to something else

Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <select className="form-control drp-po ...

Analyze items in two arrays using JavaScript and add any items that are missing

I am working on a JSON function that involves comparing objects in two different arrays, array1 and array2. The goal is to identify any missing items and either append them to array2 or create a new array called newArray1. Here is an example: const arra ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

Discover the effective method in Angular to display a solitary password validation message while dealing with numerous ones

Here is the pattern we use to validate input fields: The length of the input field should be between 6 and 15 characters. It should contain at least one lowercase letter (a-z). It should contain at least one uppercase letter (A-Z). It should contain at le ...

Tips for expanding a script that relocates a logo into a navigation consisting of several unordered lists

I recently implemented a jQuery script to center a logo within my main navigation bar only when the screen width is above 980 pixels. It was working perfectly fine with a single unordered list, but as soon as I added more unordered lists within the nav, it ...

Obtaining static images from the public directory with getStaticProps in Next.js

Next.js provides a thorough method for accessing images from the /public/ folder, where static assets are stored. This involves using Node's fs module and fetching them within the getStaticProps function. Here is an example: export async function get ...