为每个点设置阈值

时间:2015-07-29 15:20:47

标签: d3.js charts c3.js

A mockup of the 10-3-2-1

我已经使用C3.js来创建一个与此非常相似的条形图,但面临的问题是为条形图上的每个点设置一个阈值,与x轴上的值相关。例如,当X轴上的GOAL为< 10%时,y轴上的10%标记上应该有一条虚线,并且后续值即{{1} }}。

我的问题是,请问如何创建阈值或在图表上设置标记,就像它在样机上一样?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用c3用于绘制条形的相同函数来确定绘制目标线的位置,如此

<%= simple_form_for(@user) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :lang %>
    <%= f.input :firstname %>
    <%= f.input :lastname %>
    <%= f.input :email %>
    <%= f.input :born %>
    <%= f.input :gender %>
    <%= f.simple_fields_for :profile do |p| %> # the magic needed here
        <%= p.input :postal_code %>
        <%= p.input :core %>
        <%= p.input :daytime %>  
        <%= p.input :style %>
    <% end %>
    <% if @is_new %>
      <%= f.simple_fields_for :status do |s| %>
        <%= s.input :entered, as: :hidden, input_html: { value: Time.current } %>
      <% end %>
    <% end %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

<强> CSS

...

// where to draw the target lines for each data point
var scalingFactors = [0.1, 0.03, 0.02, 0.01]

// svg layer for each bar series
var barsLayers = chart.internal.main.selectAll('.' + c3.chart.internal.fn.CLASS.bars)[0]
var bars = chart.internal.main.selectAll('.' + c3.chart.internal.fn.CLASS.bar)[0];
// use the same function c3 uses to get each bars corners
var getPoints = chart.internal.generateGetBarPoints(chart.internal.getShapeIndices(chart.internal.isBarType));
// just in case there are multiple series
chart.internal.data.targets.forEach(function (series, i) {
    // for each point in the series
    series.values.forEach(function (d, j) {
        // highlight if over threshold
        if (d.value > scalingFactors[j])
            d3.select(bars[j]).classed('crossed', true);

        // get the position for our target lines
        var value = d.value;
        d.value = scalingFactors[j];
        var pos = getPoints(d, j);
        d.value = value;

        var posTopLeft = pos[1]
        var posTopRight = pos[2]

        // draw target lines
        d3.select(barsLayers[i]).append("line")
            .attr("x1", posTopLeft[0] - 10)
            .attr("y1", posTopLeft[1])
            .attr("x2", posTopRight[0] + 10)
            .attr("y2", posTopRight[1])
            .attr("stroke-width", 1)
            .style("stroke-dasharray", ("6, 4"));
    })
})

小提琴 - http://jsfiddle.net/puvhLb6x/

enter image description here