【问题标题】:Is there any way to change a label with c3js?有没有办法用 c3js 更改标签?
【发布时间】:2014-05-12 22:10:38
【问题描述】:

我正在使用新的c3js 库。有什么方法可以更改图表中一条数据的标签吗?我有一个条形图,其中每个条形都是一个美元值。我希望每个条形的标签为 100 美元而不是 100 美元。如果我将值设置为 100 美元,则库无法制作图表。有没有办法改变标签——如果不是基础价值?

【问题讨论】:

    标签: d3.js c3.js


    【解决方案1】:

    您可以为数据标签和轴刻度指定格式。看看下面的例子。

    <!doctype html>
    <html>
        <head>
            <link rel="stylesheet" type="text/css" href="./css/c3.css">
            <script src="./js/d3.min.js"></script>
            <script src="./js/c3.min.js"></script>
        </head>
        <body>
        <div class='chart'>
        <div id='chart'></div>
        </div>
        <script>
            var chart = c3.generate({
                data: {
                    columns: [
                        ['data1', 30, 200, 100, 400, 150, 250],
                        ['data2', 130, 100, 140, 200, 150, 50]
                    ],
                    type: 'bar',
                    labels: {
                        format: {
                            y: d3.format("$,")
                            //y: function (v, id) { return "Custom Format: " + id; }
                        }
                    }
                },
                axis : {
                    y : {
                        tick: {
                            format: d3.format("$,")
                            //format: function (d) { return "Custom Format: " + d; }
                        }
                    }
                }
            });
        </script>
        </body>
    </html>
    

    The resulting graph looks like this.

    查看formatting options in d3.js 或者您可以编写自己的函数(参见上面注释掉的代码)。

    【讨论】:

      【解决方案2】:

      您还可以将值显示为字符串:http://c3js.org/samples/data_stringx.html

      var chart = c3.generate({
          data: {
              x : 'x',
              columns: [
                  ['x', '$100', '$200', '$300', '$400'],
                  ['download', 30, 200, 100, 400],
                  ['loading', 90, 100, 140, 200],
              ],
              groups: [
                  ['download', 'loading']
              ],
              type: 'bar'
          },
          axis: {
              x: {
                  type: 'categorized' // this is needed to load string x value
              }
          }
      });
      

      【讨论】:

      • 如果我在数据中包含x:'x',我将收到错误 d3.v3.min.js:1 错误: 属性 x="NaN"a @ d3.v3 的值无效。 min.js:1(匿名函数)@d3.v3.min.js:3Y@d3.v3.min.js:1Aa.each@d3.v3.min.js:3Aa.attr@d3.v3.min。 js:3redraw@c3.js:1417init@c3.js:1289c3.generate@c3.js:1972(匿名函数)@c3-chart.init.js:135c@jquery.js:4p.fireWith@jquery.js: 4x.extend.ready @ jquery.js:4q @ jquery.js:4 14d3.v3.min.js:1 错误: 属性值无效 width="NaN"u @ d3.v3.min.js: 1(匿名函数)。你能告诉我为什么
      • @codelearner,可能的原因之一是axis 部分在data 内部,但它不应该存在。仔细检查正确的嵌套。这个例子有效。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      相关资源
      最近更新 更多