Amcharts 4 древовидный шар - PullRequest
0 голосов
/ 05 июля 2018

Как изменить текст / стиль в выноске на диаграмме Treemap с amchart 4?

В этом примере ниже, как мне удалить «Форд» с воздушного шара?

enter image description here

1 Ответ

0 голосов
/ 18 октября 2018

Мои искренние извинения за супер поздний ответ, недавно обнаружился вопрос, связанный с другим, не уверенным, как это проскользнуло сквозь трещины.

Это хороший вопрос как минимум по двум причинам:

  1. В то время у нас не было руководства по изменению цвета фона всплывающей подсказки .
  2. TreeMap графики не похожи на другие, мы не работаем напрямую с фактическими TreeMapSeries.

Если вы просто хотите отредактировать текст всплывающей подсказки, мы можем сделать это с помощью TreeMapSeries template, в частности, по шаблону его столбца, т.е. columns.template.tooltipText, например, используя исходную демонстрацию в качестве основы :

// The default `tooltipText` for all columns, e.g.
// `chart.series.getIndex(0).columns.template.tooltip`, is
// `"{parentName} {name}: {value}"`
//
// Let's keep {parentName} on a separate line in `tooltipText`, and play with
// font size, colors, and style. (Note we cannot nest formatting brackets.)
//
// More on string and visual formatting:
// https://www.amcharts.com/docs/v4/concepts/formatters/formatting-strings/
level1SeriesTemplate.columns.template.tooltipText =
  "[bold font-size: 22px; #fff]{parentName}[/]\n[font-size: 20px]{name}:[/] [font-size: 20px #fff]{value}[/]";

Но если вы хотите сделать больше, например, измените фон, вам нужно будет работать с самими фактическими столбцами, так как реальные объекты всплывающей подсказки недоступны в шаблонах столбцов. Вот способ сделать это для TreeMapSeries и их columns, как только они будут готовы:

// Looking over this chart type, i.e. TreeMap, we find it has a
// seriesContainer property:
// https://www.amcharts.com/docs/v4/reference/treemap/#seriesContainer_property
//
// and all containers have a "childadded" event:
// https://www.amcharts.com/docs/v4/reference/container/#childadded_event
//
// which works just as expected.
//
// More on events here:
// https://www.amcharts.com/docs/v4/concepts/event-listeners/
chart.seriesContainer.events.on("childadded", function(event) {
  // The chart will load with the initial series at first,
  // we're not interested in that.
  if (chart.series.length === 1) return;

  // Once we click a car company / TreeMap column, a new series will be generated
  // and added to the seriesContainer. Here, event.target will be the seriesContainer,
  // and event.newValue will always be the new TreeMapSeries.
  var series = event.newValue;

  // level-/depth-specific code, if you wanted
  // if (series.level === 1) {
  // }

  // The series exists, but is not ready/populated yet. In general, datavalidated
  // is a good event to check against for initial load/readiness of a series.
  series.events.once("datavalidated", function() {
    series.columns.each(function(column) {
      // In order to customize tooltip colors, we need to set getFillFromObject to false,
      // otherwise as it sounds, it'll grab color data from the parent object.
      // https://www.amcharts.com/docs/v4/reference/tooltip/#getFillFromObject_property
      // https://www.amcharts.com/docs/v4/reference/tooltip/#getStrokeFromObject_property
      column.tooltip.getFillFromObject = false;
      // column.tooltip.getStrokeFromObject = false; // not needed, since it defaults to false
      column.tooltip.background.stroke = am4core.color("#fff");
      column.tooltip.background.strokeWidth = 3;
      column.tooltip.background.strokeOpacity = 0.3;

      // background of tooltip, let's make it darker than the column's bg.
      column.tooltip.background.fill = am4core.color(
        am4core.colors.brighten(column.fill.rgb, -0.3)
      );
      // let's also make it slightly transparent.
      column.tooltip.background.fillOpacity = 0.8;

      // tooltip text color, we can also set this via string visual formatting,
      // see `tooltipText` assignment further below.
      // Every Tooltip has a Label:
      // https://www.amcharts.com/docs/v4/reference/tooltip/#label_property
      // https://www.amcharts.com/docs/v4/reference/label/
      //
      // Let's make the default color brighter than the column bg color.
      column.tooltip.label.fill = am4core.color(
        am4core.colors.brighten(column.fill.rgb, 0.7)
      );
      // alignment of text within tooltip (cannot use string visual formatting for this).
      // Let's center the text, mainly the title/parent company.
      column.tooltip.label.textAlign = "middle";
    });
  });
});

Я подготовил демо здесь:

https://codepen.io/team/amcharts/pen/07c3ca3e33b4ad955246893d19df3a6c/

Надеюсь, что это охватывает вещи, которые вы, возможно, были заинтересованы в модификации.

...