在c3.js图表​​中更改X轴的格式

时间:2017-04-25 08:42:40

标签: javascript c3.js

我正在使用相关的JSON和代码生成c3.js图表​​,我正在尝试更改X轴日期的格式,如“2016年11月”“N16”。我能得到一些帮助吗?谢谢!

    response = [["November 2016","December 2016","January 2017","February 2017","March 2017","April 2017"],["total"
    ,2,43,60,51,46,110],["mammo",1,20,34,12,12,60],["face",1,20,16,30,32,32],["body",0,3,10,9,2,18],["photo"
    ,0,19,27,12,5,21],["scan",2,24,33,39,41,89]]
    initMonthlyUsageChart(response);

function initMonthlyUsageChart(amounts) {
  var months = amounts.shift();
  c3.generate({
    bindto: '#monthly_usage_chart-js',
    data: { columns : amounts },
    axis: {
      x: {
        type: 'category',
        categories: months,
        tick: {
          rotate: 90,
          format: function (x) { // x comes in as a time string.
                x[0] = x[0].map(function(date) {
                  return date.replace(/^(\w{1}).*(\d{2})$/gi, "$1$2");
                });
            }
        }
      }
    }
  });
}

2 个答案:

答案 0 :(得分:0)

x不作为时间字符串进入,它作为类别的索引进入

因此,请更改此代码以执行您需要的操作:

      format: function (x) { // x comes in as an index
        return months[x].replace(/^(\w{1}).*(\d{2})$/gi, "$1$2");
      }

答案 1 :(得分:0)

这种方法可能有助于格式化分类图刻度格式:

var config = bindto: '#monthly_usage_chart-js',
    data: { columns : amounts },
    axis: {
      x: {
        type: 'category',
        categories: months,
        tick: {
          rotate: 90,
          format: function (x) { // x comes in as a time string.
                x[0] = x[0].map(function(date) {
                  return date.replace(/^(\w{1}).*(\d{2})$/gi, "$1$2");
                });
            }
        }
      }
    };

    config.axis.x.tick = {
        format : function(x) {
            var desiredValue = config.axis.x.categories[x];//'cause x here is a key for category chart
            return desiredValue.replace(/^(\w{1}).*(\d{2})$/gi, "$1$2");//apply your formatting stuff
        }
    };

    var chart = c3.generate(config);