javascript - 隐藏 AmChart4 上的图例标签

标签 javascript amcharts

我正在使用 amchart 折线图。

我想在图表上隐藏 amchart 图例标签。

我好不容易才发现有与labels相关的项目

console.log(chart.legend.labels.values);
console.log(chart.legend.labels.values.length)// somehow 0....

  for (key in this.chart.legend.labels.values){ // it doesn't loop...
    this.chart.legend.labels.values[key].hide();
  }

如何隐藏图例标签?

enter image description here

最佳答案

简短的回答:

chart.legend.labels.template.disabled = true;

演示:

https://codepen.io/team/amcharts/pen/17e8f139f06008c69ee45130718d5324

了解 amCharts v4's ListTemplate concept将有助于理解为什么这个答案有效,以及如何在您想迭代它的情况下使用像 chart.legend.labels 这样的对象。

ListTemplate 基本上使用一个对象/类的实际实例作为它以后将生成的所有此类对象的模板,并将其存储在其 template 属性中。 chart.legend.labelsLabelListTemplate

默认情况下,图表的图例会引用图表系列自动生成图例项,它会克隆chart.legend.markers.templatechart.legend.labels.template 然后用系列的颜色/数据填充克隆。所以如果原始标签是disabled ,它将是:

"hidden, ... removed from any processing, layout calculations, and generally treated as if it does not exist."

这就是我们想要的,因为 .hide() 可以在视觉上隐藏文本,但仍然占据相同的空间(用 CSS 术语来思考,这很像 display: none 可见性:隐藏)。

上述过程是异步的。这就是为什么您的代码 chart.legend.labels.values.length 如果直接在源代码中运行则返回 0,但如果稍后在控制台中直接运行则返回预期的数字在。如果你想遍历图例项或标签,你必须等待它们被渲染,然后使用它的 each()方法(而不是遍历 values),例如:

chart.legend.events.on("inited", function() {
    chart.legend.labels.each(function(label) {
        // Do something related to this specific label
    });
});

在上面的代码中,我们等待图例本身获取其数据、解析和渲染,然后我们检查填充的标签是否是我们想要做的。

通过提前使用模板,我们完全忽略了异步的本质。如果您想在事后对所有图例标签应用设置,对于 chart.legend.labels.template,它已经有 applyOnClones。设置为 true,因此您可以在 truefalse 之间切换 chart.legend.labels.template.disabled在您的应用程序运行期间的任何时间,它每次都会立即隐藏/显示图例的标签,并相应地更新其布局。

关于javascript - 隐藏 AmChart4 上的图例标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53363072/

相关文章:

amCharts 4 - 如何禁用滚动条以防止缩放和平移

javascript - 文件夹结构转json

javascript - 更新到 Bootstrap 3.2.0 - 导航标题对齐之后变得不对齐

javascript - 在同一页面上多次重复相同的 JS 函数

javascript - AmCharts dataLoader 不加载数据,但将数据粘贴到并使用 dataProvider 工作正常

javascript - amCharts 更改每列的宽度 (categoryAxis)

javascript - 在 amchart 中以像素为单位设置 Y 值

javascript - 在按钮单击事件上初始化 AMCharts

javascript - 使用 Firebase 函数将数据索引到 ElasticSearch,并非所有字段都被索引

java - 无法在我的 JavaScript 客户端上解码我的 Base64 字符串