【问题标题】:How to use Highchart formatter in rails?如何在 Rails 中使用 Highchart 格式化程序?
【发布时间】:2019-10-09 11:57:48
【问题描述】:

我想通过我使用 Highcharts 的 rails 项目中的图表来表示数据。我能够将其整合到项目中。如果 y 轴值为零,我不想绘制图形。 Image reference of the current scenario

我的代码,

@chart_data = [[2015, 20], [2016, 31], [2017, 5], [2018, 19], [2019, 0]]
= column_chart @chart_data, height: '375px', library: {
  xAxis: {
    title: { text: 'Years'}
  },
  yAxis: {
    stackLabels: {
      enabled: true, style: {color: '#8b9196'}
    },
    title: {
      text: 'Turn over rate')
    }
  },
  plotOptions: {
    column: {
      dataLabels: {
        enabled: true, style: { color: 'white'}
      }
    }
  },
  legend: {
    align: 'right', x: 0, verticalAlign: 'top', y: -10, floating: true, backgroundColor: 'white', borderColor: '#CCC', borderWidth: 1, shadow: false
  }
}

我发现 JavaScript 格式的解决方案没用。根据搜索,应添加如下代码

plotOptions: {
    column: {
      dataLabels: {
        enabled: true, style: { color: 'white'},
        formatter: %|function(){
          if (this.y > 0)
            return this.y;
        }|
      }
    }
  }

它抛出错误refer to the image here。我无法弄清楚获得所需结果的方法。我在 rails 中寻求帮助,因为图表已添加到视图中。

【问题讨论】:

  • 嗨@Aditya Tiwari,Highcharts 要求formatter 属性是可以调用的JS 函数。
  • 嗨@ppotaczek,我试过了,但它抛出错误。我已添加包含错误的图像。
  • 很抱歉,因为我不懂ruby,所以真的很难帮你。

标签: json charts highcharts ruby-on-rails-5 slim-lang


【解决方案1】:

我在使用带有 highcharts 库的 chartkick gem 时遇到了同样的问题。由于在 ruby​​ 代码上调用 js 函数不起作用,我将其添加到 application.js 文件中,因此当加载图表时,此配置将应用于图表。如果您只想在几个图表中使用该配置,则必须仅在所需的视图中使用它。

const Chartkick = require("chartkick");
Chartkick.use(require("highcharts"));

Chartkick.options = {
  library: {
    plotOptions: { 
      column: {
        dataLabels: {
          formatter: function() {
            return (this.y!=0) ? this.y : "";
          }
        }
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2021-07-19
    • 2019-09-05
    • 1970-01-01
    • 2017-08-09
    • 2013-06-22
    • 2012-09-30
    相关资源
    最近更新 更多