Dimple JS添加垂直线

时间:2015-03-30 17:57:28

标签: d3.js dimple.js

我想在Dimple画一条垂直线。我看过这篇文章:How to draw a vertical line with dimple?

然而,提供的示例并不适用于我。它只是添加了一个点而不是我想画一条线。我无法在文档中找到任何内容,也无法在StackOverflow上找到任何内容,也无法通过谷歌搜索找到任何内容,我认为这应该是一件容易的事情 - 但到目前为止,事实证明并非如此。任何帮助将不胜感激。

小提琴:http://jsfiddle.net/4w6gkq5s/27/

<!DOCTYPE html>
<html>
<body>
<div id="chartContainer">
  <script src="http://dimplejs.org/lib/d3.v3.4.8.js"></script>
  <script src="http://dimplejs.org/dist/dimple.v2.1.2.min.js"></script>
  <script type="text/javascript">
    var svg = dimple.newSvg("#chartContainer", 590, 400);
    d3.tsv("http://dimplejs.org/data/example_data.tsv", function (data123) {
      var data = [{'name': "name1", "percentChange": 120}, {'name': "name2", "percentChange": 80}, {'name': "name3", "percentChange": 100}];

      var myChart = new dimple.chart(svg, data);
      myChart.defaultColors = [ new dimple.color("#177c5f") ];

      myChart.defaultColors = [
      new dimple.color("#3d5739"), // green
        ];

      var x2 = myChart.addMeasureAxis("x", "percentChange");
      x2.title = "Percent of last month's sales"
      var y = myChart.addCategoryAxis("y", "name");
      y.addOrderRule("name");
      y.title = null;
      y.showGridLines = true;

      /*Regional average*/
      var y2 = myChart.addPctAxis("y", "Dummy");
      var s3 = myChart.addSeries("Regional", dimple.plot.area, [x2, y2]);
      s3.data = [{
        "Regional": "Regional",
        "Dummy": 1,
        "percentChange": 105
      }];

      var s = myChart.addSeries(["percentChange", "name"], dimple.plot.bar);
      s.barGap = .86;

      // Set some custom display elements for each series shape
      s.afterDraw = function (shape, data) {

        var shape = d3.select(shape);

        // Add some bar labels for the yValue
        svg.append("text")
        .attr("x", parseFloat(shape.attr("x")) + 40)
        .attr("y", parseFloat(shape.attr("y")) - 5)
        .style("text-anchor", "middle")
        .style("font-size", "16px")
        .style("fill", "#73b7e8")
        .style("pointer-events", "none")
        .text(data.cy);
      };

      s.addEventHandler("mouseover", onHover);
      s.addEventHandler("mouseleave", onLeave);
    myChart.draw();

   function onHover(e) {
     e.selectedShape[0][0].style.fill = "#00924f";
   };
   function onLeave(e) {
      e.selectedShape[0][0].style.fill = "#3d5739";
   };
  });
  </script>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:5)

这种方法不适用于x上的测量轴。然而,在这种情况下,解决方案实际上更简单。绘图后,您可以添加一行d3:

svg.append("line")
    .attr("x1", x._scale(105))
    .attr("x2", x._scale(105))
    .attr("y1", myChart._yPixels())
    .attr("y2", myChart._yPixels() + myChart._heightPixels())
    .style("stroke", "red")
    .style("stroke-dasharray", "3");

小提琴:http://jsfiddle.net/d3jo0uu5/1/

这在凹坑中使用了几个内部方法来表示高度和宽度,以及x轴刻度用于水平定位线。我已经将它变成了红色和虚线但是改变了样式线,你可以根据自己的意愿对其进行格式化 - 或者设置一个类而不是在css中设置外观。