简体   繁体   English

amcharts4 在对数值轴上处理零值的正确方法

[英]amcharts4 proper way to handle zero values on logarithmic value axis

I want to display some data with high variety in amcharts4, so I like to use the logarithmic scale on the value axis.我想在amcharts4中显示一些种类繁多的数据,所以我喜欢在值轴上使用对数刻度。 Unfortunately the data contain some zero values, which of course can't be displayed with logarithmic scale.不幸的是,数据包含一些零值,当然不能用对数刻度显示。

I tried to change the zero values to 1 before rendering the chart, which would work, but now the values are not correct any more.我尝试在渲染图表之前将零值更改为 1,这会起作用,但现在这些值不再正确。

data.forEach(item => {
  for (const key in item) {
    if (item[key] === 0) {
      item[key] = 1;
    }
  }
});

Is there any better way to handle zero values with logarithmic value axis, that I can display the correct data?有没有更好的方法用对数值轴处理零值,我可以显示正确的数据?

Here is a code pen, which shows my current solution.是一个代码笔,它显示了我当前的解决方案。

Edit编辑

As of version 4.9.34, treatZeroAs is officially supported.从 4.9.34 版本开始, treatZeroAs得到官方支持。 Just set it on the value axis to the desired value to remap your zero values to:只需将其在值轴上设置为所需的值,即可将您的零值重新映射为:

valueAxis.treatZeroAs = 0.1;

Updated codepen . 更新了代码笔

The below workaround isn't needed anymore, but you may find the value axis adapter snippet helpful in changing the first label when using treatZeroAs .不再需要以下解决方法,但您可能会发现值轴适配器片段有助于在使用treatZeroAs时更改第一个标签。

Old method - pre 4.9.34旧方法 - 4.9.34 之前

There doesn't appear to be a direct equivalent to v3's treatZeroAs property, which automatically handled this sort of thing.似乎没有直接等价于 v3 的treatZeroAs属性,它会自动处理这类事情。 Pre-processing the data is one step, but you can also copy the original value into a separate object property and use a series tooltip adapter to dynamically show your actual value:预处理数据是一个步骤,但您也可以将原始值复制到单独的对象属性中,并使用系列工具提示适配器来动态显示您的实际值:

data.forEach(item => {
  for (const key in item) {
    if (item[key] <= 0) {
      item[key+"_actual"] = item[key]; //copy the original value into a different property
      item[key] = 1;
    }
  }
});
// ...

//display actual data that was re-mapped if it exists
chart.series.each((series) => {
  series.adapter.add("tooltipText", (text, target) => {
    if (target.dataFields) {
      let valueField = target.dataFields.valueY;
      let tooltipData = target.tooltipDataItem;
      if (tooltipData.dataContext[valueField + "_actual"] !== undefined) { 
        return '{' + valueField + '_actual}';
      }
      else {
        return text;
      }
    }
    else {
      return text;
    }
  })
});

If you want to fake a zero label, you can use an adapter for that as well since your smallest value in this case will be 1:如果您想伪造零标签,您也可以为此使用适配器,因为在这种情况下您的最小值将为 1:

//fake the zero axis label
valueAxis.renderer.labels.template.adapter.add("text", (text) => {
  if (text === "1") {
    return "0"
  }
  else {
    return text;
  }
})

Codepen 代码笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM