如何在 Amserial 图表中添加图例 [英] How to add legends in Amserial charts

查看:23
本文介绍了如何在 Amserial 图表中添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 AngularJS 应用程序中使用 Amcharts 创建一个简单的条形图.以下是我在控制器中的代码:

 let empChart;让 empBarGraph;让 empLine;const writeemp = 数据 =>{常量{全部的,雇员,} = 数据;empChart.dataProvider = e;empChart.write('emp');empChart.validateData();};AmCharts.handleLoad();var configChart = 函数 () {empChart = new AmCharts.AmSerialChart();empChart.categoryField = "状态";empChart.labelRotation = 90;var yAxis = new AmCharts.ValueAxis();yAxis.position = "左";empChart.addValueAxis(yAxis);empBarGraph = new AmCharts.AmGraph();empBarGraph.valueField = "计数";empBarGraph.type = "列";empBarGraph.fillAlphas = 1;empBarGraph.lineColor = "#f0ab00";empBarGraph.valueAxis = yAxis;empChart.addGraph(empBarGraph);empChart.write('empChart');$http.get(hostNameService.getHostName()+"/dashboard/employees/statecount").then(response => writeemp(response.data));}

html 中的代码:

 

<div id="empChart"></div>

这将返回 x 轴上的 State 值和 y 轴上的计数.我想根据 state 的值过滤图表,但不确定如何为此图表创建图例.任何人都可以建议我如何使用图例.我想为正在返回的状态值创建图例.

解决方案

您可以使用基于 OO 的语法添加图例,方法是通过 new AmCharts.AmLegend() 创建图例对象并添加它通过调用图表的 addLegend 方法到类:

var legend = new AmCharts.AmLegend();empChart.addLegend(图例);

如果您希望图例在将鼠标悬停在列上时显示值,您需要将 ChartCursor 添加到您的图表中:

var cursor = new AmCharts.ChartCursor();empChart.addChartCursor(cursor);

您可以通过设置 valueText 属性来更改列翻转时图例显示的内容.它允许在 balloonTextlabelText 等字段中使用相同的 [shortcodes],例如legend.valueText = "[[category]]: [[value]]".如果您需要像在之前的问题中一样自定义它动态返回的文本,您也可以使用 set its valueFunction.图例对象中可用的所有属性都可以在 AmLegend API 文档中找到.

更新:

图例仅适用于图形对象,因此没有开箱即用的方法可让您将每一列表示为可切换其他列可见性的图例项,除非您愿意重新组织数据集并为每个状态使用不同的图形对象.解决方法是使用图例的自定义 data 数组并添加一些事件处理,以便单击自定义数据项通过取消设置您的 count valueField 添加/删除切换在数据提供者中.

以下带注释的代码可以完成您要执行的操作:

//创建图例,但在填充 dataProvider 之前禁用它,//因为您使用 AJAX 检索数据var Legend = new AmCharts.AmLegend();图例.启用 = 假;chart.addLegend(图例);chart.toggleLegend = false;//处理对自定义数据条目标记和标签的点击的回调var handleLegendClick = function(legendEvent) {//设置自定义标志,以便 dataUpdated 事件不会无限触发LegendEvent.chart.toggleLegend = true;//下面打开和关闭标记.//隐藏"列的唯一方法是取消设置数据索引处的valueField,//所以一个临时的storedCount"属性被添加到存储//原始值,以便在切换图例标记时可以恢复该值//重新开始如果(未定义!== LegendEvent.dataItem.hidden &&legendEvent.dataItem.hidden){LegendEvent.dataItem.hidden = false;LegendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count = legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].storedCount;//恢复值} 别的 {//关闭标记LegendEvent.dataItem.hidden = true;LegendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].storedCount = legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count;//存储值LegendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count = undefined;//设置为未定义隐藏列}LegendEvent.chart.validateData();//重新绘制图表}chart.addListener('dataUpdated', function(e) {var LegendDataItems;//用于存储图例的自定义数据数组.如果(e.chart.toggleLegend === true){//用户是否在切换图例标记?在此停止,因为 dataProvider 将在 handleLegendClick 中更新e.chart.toggleLegend = false;返回;}//如果此时,数据提供者已更新.//重建数据数组.//通过获取状态、设置颜色和存储索引来初始化//稍后切换列LegendDataItems = e.chart.dataProvider.map(function(dataElement, idx) {返回 {'标题':dataElement.state,'颜色':graph.lineColor,'stateIdx': idx//用于切换}});//如果未启用图例,那么我们将第一次设置它.//打开它并附加事件处理程序如果(e.chart.legend.enabled === false){e.chart.legend.enabled = true;e.chart.legend.switchable = true;e.chart.legend.addListener('clickMarker', handleLegendClick);e.chart.legend.addListener('clickLabel', handleLegendClick);}//更新图例自定义数据并重绘图表e.chart.legend.data = legendDataItems;e.chart.validateNow();});

这是说明这一点的小提琴:http://jsfiddle.net/g254sdq5/1/

I am using Amcharts in my AngularJS Application to create a simple bar chart.The following is my code in the controller:

        let empChart;
        let empBarGraph;
        let empLine;
        const writeemp = data => {
            const {
                total,
                employees,
            } = data;

            empChart.dataProvider = e;
            empChart.write('emp');
            empChart.validateData();
        };

        AmCharts.handleLoad();

        var configChart = function () {


            empChart = new AmCharts.AmSerialChart();
            empChart.categoryField = "state";
            empChart.labelRotation = 90;

            var yAxis = new AmCharts.ValueAxis();
            yAxis.position = "left";
            empChart.addValueAxis(yAxis);


            empBarGraph = new AmCharts.AmGraph();
            empBarGraph.valueField = "count";
            empBarGraph.type = "column";
            empBarGraph.fillAlphas = 1;
            empBarGraph.lineColor = "#f0ab00";
            empBarGraph.valueAxis = yAxis;
            empChart.addGraph(empBarGraph);
            empChart.write('empChart');


            $http.get(hostNameService.getHostName()+"/dashboard/employees/statecount")
                .then(response => writeemp(response.data));
        }

Code in html:

                       <div class='panel-body'>
                            <div id="empChart"></div>
                        </div>

This would return me the values of State on x-axis and count on y-axis. I wanted to filter the chart based on the value of state and was not sure how to create the legends for this chart. could anyone suggest me on how to use legends. I want to create legends for the state value that is being returned.

解决方案

You can add a legend using the OO-based syntax by creating a legend object through new AmCharts.AmLegend() and adding it to the class by calling the chart's addLegend method:

var legend = new AmCharts.AmLegend();
empChart.addLegend(legend);

If you want the legend to show values upon hovering over a column, you need to add a ChartCursor to your chart:

var cursor = new AmCharts.ChartCursor();
empChart.addChartCursor(cursor);

You can change what the legend displays upon column rollover by setting the valueText property. It allows for the same [shortcodes] used in fields like balloonText and labelText, e.g. legend.valueText = "[[category]]: [[value]]". You can also use set its valueFunction if you need to customize the text it returns dynamically like in your previous questions. All of the properties available in the legend object can be found in the AmLegend API documentation.

Updated:

Legends work off of graph objects only, so there isn't an out of the box method that allows you to represent each column as a legend item that toggles the other columns' visibility unless you're willing to reorganize your dataset and use different graph objects for each state. A workaround for this is to use the the legend's custom data array and add some event handling so that clicking on the custom data items adds/removes a toggle by unsetting your count valueField in the dataProvider.

The following annotated code accomplishes what you're trying to do:

  //create the legend but disable it until the dataProvider is populated,
  //since you're retrieving your data using AJAX
  var legend = new AmCharts.AmLegend();
  legend.enabled = false;

  chart.addLegend(legend);
  chart.toggleLegend = false;

  // Callback that handles clicks on the custom data entry markers and labels
  var handleLegendClick = function(legendEvent) {
    //Set a custom flag so that the dataUpdated event doesn't fire infinitely
    legendEvent.chart.toggleLegend = true; 

    // The following toggles the markers on and off.
    // The only way to "hide" a column is to unset the valueField at the data index,
    // so a temporary "storedCount" property is added to the dataProvider that stores the 
    // original value so that the value can be restored when the legend marker is toggled
    // back on
    if (undefined !== legendEvent.dataItem.hidden && legendEvent.dataItem.hidden) {
      legendEvent.dataItem.hidden = false;
      legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count = legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].storedCount; //restore the value
    } else {
    // toggle the marker off
      legendEvent.dataItem.hidden = true;
      legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].storedCount = legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count;  //store the value
      legendEvent.chart.dataProvider[legendEvent.dataItem.stateIdx].count = undefined; //set to undefined to hide the column
    }
    legendEvent.chart.validateData(); //redraw the chart
  }


  chart.addListener('dataUpdated', function(e) {
    var legendDataItems; //used to store the legend's custom data array.

    if (e.chart.toggleLegend === true) {
      //is the user toggling a legend marker? stop here as the dataProvider will get updated in handleLegendClick
      e.chart.toggleLegend = false;
      return;
    }

    // if we're at this point, the data provider was updated. 
    // reconstruct the data array.
    // initialize by grabbing the state, setting a color and stoing the index
    // for toggline the columns later
    legendDataItems = e.chart.dataProvider.map(function(dataElement, idx) {
      return {
        'title': dataElement.state,
        'color': graph.lineColor,
        'stateIdx': idx //used in toggling
      }
    });

    // if the legend is not enabled, then we're setting this up for the first time.
    // turn it on and attach the event handlers
    if (e.chart.legend.enabled === false) {
      e.chart.legend.enabled = true;
      e.chart.legend.switchable = true;

      e.chart.legend.addListener('clickMarker', handleLegendClick);
      e.chart.legend.addListener('clickLabel', handleLegendClick);
    }

    // update the legend custom data and redraw the chart
    e.chart.legend.data = legendDataItems;
    e.chart.validateNow();
  });

Here's a fiddle that illustrates this: http://jsfiddle.net/g254sdq5/1/

这篇关于如何在 Amserial 图表中添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆