amcharts stacked barchart - 突出显示值(更改alpha)以响应事件

问题描述 投票:2回答:2

我有一张用amcharts制作的条形图。我在this example之后建立了堆积条形图。

如果我将鼠标悬停在我页面中的其他元素(例如表格)上,我正试图更改框的alpha(或颜色)。例如,如果用户在我页面上某处的相应表格单元格上悬停,我想更改(2003,Europe)框的alpha(或颜色)。

我已经将我的图表放在一个角度为6的组件中,但我想这只要我正确捕获输入更改事件并不重要。


编辑1。

我仍然在努力导航物体。我建立了一个条形图,看起来不错

  createSeries(field, name) {
    var series = this.chart.series.push(new am4charts.ColumnSeries());
    series.name = name;
    series.dataFields.valueY = field;
    series.dataFields.categoryX = "country";
    series.sequencedInterpolation = true;
    series.columns.template.fillOpacity = 0.5

    // Make it stacked
    series.stacked = true;

    // Configure columns
    series.columns.template.width = am4core.percent(60);
    series.columns.template.tooltipText = "[bold]{name}[/]\n[font-size:14px]{categoryX}: {valueY}";
    console.log(series)
    return series
  }

我有四个列系列,一个用于我的数据中的每个字段。我可以通过字段格式化系列。

  grabBar(country, field) {
    // If you don't have access to the chart code in your angular scope,
    // use am4core global.
    // no reason to loop through ALL series/columns, just whipped this up quick
    let foundBar: am4charts.XYSeries | null;
    this.chart.series.each(series => {
      if (series.dataFields.categoryY == field) {
        console.log("yay")
        series.dataItems.values
      }
    });
    return foundBar;

但我无法找到一种方法来访问与国家和特定领域相对应的元素。我看到的是四个,每个领域一个,ColumnSeries没有任何columns财产。我的am4core.registry.baseSprites[0]在那里没有series

这是我的完整代码:

import { Component, OnInit, NgZone, Input } from '@angular/core';
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";
import { CountryItinerary, Team } from "../model/classes"

am4core.useTheme(am4themes_animated);



@Component({
  selector: 'barchart-distance',
  templateUrl: './barchart-distance.component.html',
  styleUrls: ['./barchart-distance.component.scss']
})
export class BarchartDistanceComponent implements OnInit {

  constructor(private zone: NgZone) { }
  _selectedTeam: Team | null

  @Input() 
  set selectedTeam(team: Team | null) {
    this._selectedTeam = team;
    if (team) {
      this.changeColorToBar(team.isocode, "week_1", 1.0)
    }
  }

  chart: am4charts.XYChart
  categoryAxis: any
  valueAxis: any

  ngOnInit() {

  }

  grabBar(country, weekId) {
    // If you don't have access to the chart code in your angular scope,
    // use am4core global.
    // no reason to loop through ALL series/columns, just whipped this up quick
    let foundBar: am4charts.XYSeries | null;
    this.chart.series.each(series => {
      if (series.name == "Week_2") {
        console.log(series.dataItem)
      }

    });
    return foundBar;
  }

  changeColorToBar(country, weekId, opacity) {
    let bar = this.grabBar(country, weekId)
    if (bar) {
      bar.background.fillOpacity = opacity
    }
  }

  createSeries(field, name) {
    var series = this.chart.series.push(new am4charts.ColumnSeries());
    series.name = name;
    series.dataFields.valueY = field;
    series.dataFields.categoryX = "country";
    series.sequencedInterpolation = true;
    series.columns.template.fillOpacity = 0.5

    // Make it stacked
    series.stacked = true;

    // Configure columns
    series.columns.template.width = am4core.percent(60);
    series.columns.template.tooltipText = "[bold]{name}[/]\n[font-size:14px]{categoryX}: {valueY}";
    console.log(series)
    return series
  }

  drawWithData() {
    this.zone.runOutsideAngular(() => {
      this.chart = am4core.create("chartdiv2", am4charts.XYChart);
      let data = [
        new CountryItinerary("Italy", "IT", [10, 15, 15, 22]),
        new CountryItinerary("Germany", "DE", [20, 30, 40, 24]),
        new CountryItinerary("Greece", "GR",  [13, 10, 20, 15])
      ]

      this.chart.data = data.map ((el) => {
        let newEl = { "country": el.isocode }
        el.distances.forEach((item, index) => {
          newEl["week_" + index] = item
        })
        return newEl   
      })
      console.log(this.chart.data)

      this.categoryAxis = this.chart.xAxes.push(new am4charts.CategoryAxis());
      this.categoryAxis.dataFields.category = "country";
      this.categoryAxis.renderer.grid.template.location = 0;

      this.valueAxis = this.chart.yAxes.push(new am4charts.ValueAxis());
      this.valueAxis.renderer.inside = true;
      this.valueAxis.renderer.labels.template.disabled = true;
      this.valueAxis.min = 0;

      let numberOfTrips = data[0].distances.length
      for (let i = 0; i < numberOfTrips; i++) {
        this.createSeries("week_" + i, "Week_" + i)
     } 
     console.log(this.chart.series)


    })
  }

  ngAfterViewInit() {
    this.drawWithData()
  }

}

在那里,series.dataItem.dataContext未定义。

angular typescript hover amcharts amcharts4
2个回答
2
投票

(在他提供了实际的角度代码之后添加了一个不同的答案,以及事情正在为他提供的地方,我之前的答案似乎远不那么相关。)

我将自己的方法作为Input()传递给表组件,但确保使用箭头函数,因此它保留了此图表组件的范围:

  selectTeam = (team, weekN) => {
    this._selectedTeam = team;
    if (team) {
      this.changeColorToBar(team.isocode, weekN, 1.0);
    }
  }

对于列本身,由于您要更改的属性的值也可能会更改,因此使用States并直接在对象上实际调整属性可能没有意义。在这种情况下,您将直接更改fillOpacity,而不是列background

  changeColorToBar(country, weekId, opacity) {
    let bar = this.grabBar(country, weekId);
    if (bar && bar !== this.currentBar) {
      if (this.currentBar) this.currentBar.fillOpacity = 0.5; // Default
      bar.fillOpacity = opacity;
      this.currentBar = bar;
    }
  }

我没有找到图表,系列和列的问题。时间当然可能是一个问题,即图表和系列必须实际加载,但这可能发生在用户徘徊时:

  grabBar(country, weekId = 0) {
    const totalSeries = this.chart.series.length;
    for (let i = 0; i < totalSeries; ++i) {
      const series = this.chart.series.getIndex(i);
      if (series.name === "Week_" + weekId) {
        const totalColumns = series.columns.length;
        for (let c = 0; c < totalColumns; ++c) {
          const column = series.columns.getIndex(c);
          if (
            column.dataItem.dataContext.country === country
          ) {
            return column;
          }
        }
      }
    }
  }

这是一个演示:

https://stackblitz.com/edit/so-55597531-table-input-chart

如果你仍然无法在系列中找到列,那么可能会在StackBlitz上找到你的项目样本,这样我们就可以尝试查看出错的地方。


2
投票

您将需要获取可用于确定图表中Column的信息。例如。图表行/列标题或应用中的数据。然后,您可以遍历图表的系列以匹配其数据,例如国家名称,并通过他们的columns'dataItem.dataContext.year迭代以匹配年份。

有了年份和国家,我们可以从一个系列中获取一个列,例如:

function grabColumn(year, country) {
  // If you don't have access to the chart code in your angular scope,
  // use am4core global.
  // no reason to loop through ALL series/columns, just whipped this up quick
  let foundColumn;
  am4core.registry.baseSprites[0].series.each(series => {
    if (series.name === country) {
      series.columns.each(column => {
        if (column.dataItem.dataContext.year === year) {
          foundColumn = column;
        }
      });
    }
  });
  return foundColumn;
}

要更改colors,虽然您可以直接设置fillcolumn属性,但我建议使用States,例如将此添加到createSeries方法的末尾:

  const highlightState = series.columns.template.states.create('highlight');
  highlightState.properties.fill = am4core.color("#f00"); // These are fine, too: // am4core.color("red"); // "red";

所以给出一个表:

  <table>
    <thead><tr><td></td><th>Europe</th><th>North America</th><th>Asia</th><th>Latin America</th><th>Middle East</th><th>Africa</th></tr></thead>
    <tbody>
      <tr><th>2003</th><td>2.5</td><td>2.5</td><td>2.1</td><td>1.2</td><td>0.2</td><td>0.1</td></tr>
      <tr><th>2004</th><td>2.6</td><td>2.7</td><td>2.2</td><td>1.3</td><td>0.3</td><td>0.1</td></tr>
      <tr><th>2005</th><td>2.8</td><td>2.9</td><td>2.4</td><td>1.4</td><td>0.3</td><td>0.1</td></tr>
    </tbody>
  </table>

将鼠标悬停在数据单元格上,其行的第一个子节点保存年份,标题行的第n个子节点保存该国家/地区。我们可以使用它来获取正确的列并更改其状态,而不是querySelector / addEventListener,这将是您的角度内容:

const $headerRow = document.querySelector('thead tr');
let highlightedColumn;
document.querySelector('tbody').addEventListener('mouseover', event => {
  if (event.target.matches('td')) {
    const year = event.target.parentElement.getElementsByTagName('th')[0].childNodes[0].nodeValue;
    const siblings = event.target.parentNode.children;
    const totalSiblings = siblings.length;
    let country;
    for(let i = 1; i < totalSiblings; ++i) {
      if (siblings[i] === event.target) {
        country = $headerRow.children[i].childNodes[0].nodeValue;
        break;
      }
    }

    const column = grabColumn(year, country);
    if (highlightedColumn !== column) {              
      if (highlightedColumn) {
        highlightedColumn.setState('default');
      }
      column.setState('highlight');
      highlightedColumn = column;
    }
  }
});

您还需要确保有一个正确的mouseout事件来重置突出显示的列。

这是一个演示:

https://codepen.io/team/amcharts/pen/36fae5caa2538b22fc2111666749c0b3

© www.soinside.com 2019 - 2024. All rights reserved.