GVKun编程网logo

javascript – 如何“转储”使用LinkedBrush插件为mpld3选择的点?

14

对于javascript–如何“转储”使用LinkedBrush插件为mpld3选择的点?感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于java–使用LinkedHashMap实现LRU缓存、

对于javascript – 如何“转储”使用LinkedBrush插件为mpld3选择的点?感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于java – 使用LinkedHashMap实现LRU缓存、javascript onkeydown,onkeyup,onkeypress,onclick,ondblclick_javascript技巧、javascript – d3 v4实现中d3-brush的JS错误、javascript – D3.js – 如何选择工作 – 需要澄清Mike的文章的有用信息。

本文目录一览:

javascript – 如何“转储”使用LinkedBrush插件为mpld3选择的点?

javascript – 如何“转储”使用LinkedBrush插件为mpld3选择的点?

我正在尝试实现一个插件,允许用户转储有关LinkedBrush插件选择的点的相关信息.我认为我的问题与 this example有关.我通过HTMLTooltip插件将每个点都绑定了元信息.理想情况下,我也能以某种方式转储它.在我链接的示例中,信息通过提示输出.我希望能够将此信息保存到某种文本文件中.

略有不同:如何确定LinkedBrush工具选择了散点图中的哪些点,以便我可以保存信息?

解决方法

为了解决这个问题,我最终只编辑了LinkedBrush插件代码.我添加了一个按钮,单击该按钮时,使用brush.extent()输出画笔窗口的范围.这将打印最小和最大x和y坐标.我将基本上使用这些坐标追溯到输入数据集并确定哪些点落在画笔的边界内.如果有人对如何解决这个问题有更好的了解,我会欢迎它.

class LinkedBrush(plugins.PluginBase):
JAVASCRIPT="""
  mpld3.LinkedBrushPlugin = mpld3_LinkedBrushPlugin;
  mpld3.register_plugin("linkedbrush",mpld3_LinkedBrushPlugin);
  mpld3_LinkedBrushPlugin.prototype = Object.create(mpld3.Plugin.prototype);
  mpld3_LinkedBrushPlugin.prototype.constructor = mpld3_LinkedBrushPlugin;
  mpld3_LinkedBrushPlugin.prototype.requiredProps = [ "id" ];
  mpld3_LinkedBrushPlugin.prototype.defaultProps = {
    button: true,enabled: null
  };
  function mpld3_LinkedBrushPlugin(fig,props) {
    mpld3.Plugin.call(this,fig,props);
    if (this.props.enabled === null) {
      this.props.enabled = !this.props.button;
    }
    var enabled = this.props.enabled;
    if (this.props.button) {
      var BrushButton = mpld3.ButtonFactory({
        buttonID: "linkedbrush",sticky: true,actions: [ "drag" ],onActivate: this.activate.bind(this),onDeactivate: this.deactivate.bind(this),onDraw: function() {
          this.setState(enabled);
        },icon: function() {
          return mpld3.icons["brush"];
        }
      });
      this.fig.buttons.push(BrushButton);
      var my_icon = "data:image/png;base64,longstring_that_I_redacted";
      var SaveButton = mpld3.ButtonFactory({
            buttonID: "save",sticky: false,onActivate: this.get_selected.bind(this),icon: function(){return my_icon;},});
      this.fig.buttons.push(SaveButton);
    }
    this.extenthttps://www.jb51.cc/tag/rush/" target="_blank">rush";
  }
  mpld3_LinkedBrushPlugin.prototype.activate = function() {
    if (this.enable) this.enable();
  };
  mpld3_LinkedBrushPlugin.prototype.deactivate = function() {
    if (this.disable) this.disable();
  };
  mpld3_LinkedBrushPlugin.prototype.get_selected = function() {
    if (this.get_selected) this.get_selected();
  };
  mpld3_LinkedBrushPlugin.prototype.draw = function() {
    var obj = mpld3.get_element(this.props.id);
    if (obj === null) {
      throw "LinkedBrush: no object with id='" + this.props.id + "' was found";
    }
    var fig = this.fig;
    if (!("offsets" in obj.props)) {
      throw "Plot object with id='" + this.props.id + "' is not a scatter plot";
    }
    var dataKey = "offsets" in obj.props ? "offsets" : "data";
    mpld3.insert_css("#" + fig.figid + " rect.extent." + this.extentClass,{
      fill: "#000","fill-opacity": .125,stroke: "#fff"
    });
    mpld3.insert_css("#" + fig.figid + " path.mpld3-hidden",{
      stroke: "#ccc !important",fill: "#ccc !important"
    });
    var data+ obj.props[dataKey];
    var brush = fig.getBrush();
    var dataByAx = [];
    fig.axes.forEach(function(ax) {
      var axData = [];
      ax.elements.forEach(function(el) {
        if (el.props[dataKey] === obj.props[dataKey]) {
          el.group.classed(dataClass,true);
          axData.push(el);
        }
      });
      dataByAx.push(axData);
    });
    var allData = [];
    var dataToBrush = fig.canvas.selectAll("." + dataClass);
    var currentAxes;
    function brushstart(d) {
      if (currentAxes != this) {
        d3.select(currentAxes).call(brush.clear());
        currentAxes = this;
        brush.x(d.xdom).y(d.ydom);
      }
    }
    function brushmove(d) {
      var data = dataByAx[d.axnum];
      if (data.length > 0) {
        var ix = data[0].props.xindex;
        var iy = data[0].props.yindex;
        var e = brush.extent();
        if (brush.empty()) {
          dataToBrush.selectAll("path").classed("mpld3-hidden",false);
        } else {
          dataToBrush.selectAll("path").classed("mpld3-hidden",function(p) {
            return e[0][0] > p[ix] || e[1][0] < p[ix] || e[0][1] > p[iy] || e[1][1] < p[iy];
          });
        }
      }
    }
    function brushend(d) {
      if (brush.empty()) {
        dataToBrush.selectAll("path").classed("mpld3-hidden",false);
      }
    }
    this.get_selected = function(d) {
        var brush = fig.getBrush();
        var extent = brush.extent();
        alert(extent);
    }
    this.enable = function() {
      this.fig.showBrush(this.extentClass);
      brush.on("brushstart",brushstart).on("brush",brushmove).on("brushend",brushend);
      this.enabled = true;
    };
    this.disable = function() {
      d3.select(currentAxes).call(brush.clear());
      this.fig.hideBrush(this.extentClass);
      this.enabled = false;
    };
    this.disable();
  };
    """
    def __init__(self,points,button=True,enabled=True):
        if isinstance(points,mpl.lines.Line2D):
            suffix = "pts"
        else:
            suffix = None
        self.dict_ = {"type": "linkedbrush","button": button,"enabled": False,"id": utils.get_id(points,suffix)}

java – 使用LinkedHashMap实现LRU缓存

java – 使用LinkedHashMap实现LRU缓存

我试图使用LinkedHashMap实现LRU缓存.
在LinkedHashMap( http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html)的文档中,它说:

请注意,如果将键重新插入到地图中,则插入顺序不受影响.

但是当我做下面的表达

public class LRUCache<K,V> extends LinkedHashMap<K,V> {
    private int size;

    public static void main(String[] args) {
        LRUCache<Integer,Integer> cache = LRUCache.newInstance(2);
        cache.put(1,1);
        cache.put(2,2);
        cache.put(1,1);
        cache.put(3,3);

        System.out.println(cache);
    }

    private LRUCache(int size) {
        super(size,0.75f,true);
        this.size = size;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return size() > size;
    }

    public static <K,V> LRUCache<K,V> newInstance(int size) {
        return new LRUCache<K,V>(size);
    }

}

输出是

{1=1,3=3}

这表明重新插入确实影响了订单.
有谁知道任何解释吗?

解决方法

正如@Jeffrey所说,你正在使用accessOrder.创建LinkedHashMap时,第三个参数指定顺序如何更改.
"true for access-order,false for insertion-order"

对于LRU的更详细的实现,你可以看看这个
@L_301_1@

javascript onkeydown,onkeyup,onkeypress,onclick,ondblclick_javascript技巧

javascript onkeydown,onkeyup,onkeypress,onclick,ondblclick_javascript技巧

这里给出一段测试代码:


测试结果为:
keydown
keypress
keyup
显而易见,事件发生的顺序是: keydown --> keypress --> keyup
当按住一个键一段时间后再放开时,结果为:
keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
...
keyup
n个keydown和n个keypress,1个keyup,系统设置的时间间隔.
关于click和dblclick
前段时间群里面的一个朋友问过一个关于click和dblclick的问题,在这里同时也整理一下,他的要求是click和dblclick有不同的事件处理程序,但是如果触发了dblclick则对click不做处理.如何解决?
我们先来看一下事件的发生情况,测试代码如下:


双击时结果如下:
click
dblclick
当放慢点击速度时,结果如下:
click
click
click
可见,dblclick时,首先会触发一个click事件,然后如果在系统设置的双击延迟时间范围内有第二次click事件,则被认为是dblclick事件.
那么如何解决这位朋友提出的问题呢?给出代码如下:


双击测试结果如下:
dblclick
dblclick
dblclick
dblclick

javascript – d3 v4实现中d3-brush的JS错误

javascript – d3 v4实现中d3-brush的JS错误

此示例适用于d3 v3版本.它是 this sample的修剪版本,在与按钮交互时,画笔在其新位置动画.

我实际上是尝试使用d3 v4版本来做this.

修剪是为了识别关注的区域.修剪过的代码是

var margin = { top: 10,right: 10,bottom: 100,left: 40 },margin2 = { top: 430,bottom: 20,width = 960 - margin.left - margin.right,height = 500 - margin.top - margin.bottom,height2 = 500 - margin2.top - margin2.bottom;

  var parseDate = d3.timeParse("%b %Y");

  var x = d3.scaleTime().range([0,width]),x2 = d3.scaleTime().range([0,y = d3.scaleLinear().range([height,0]),y2 = d3.scaleLinear().range([height2,0]);

var xAxis = d3.axisBottom(x),xAxis2 = d3.axisBottom(x2),yAxis = d3.axisLeft(y);

  var brush = d3.brushX(x2)
    .on("brush end",brushed);

  var area1 = d3.area()
    .curve(d3.curveMonotoneX)
    .x(function(d) { return x(d.date); })
    .y0(height)
    .y1(function(d) { return y(d.price); });

var area2 = d3.area()
    .curve(d3.curveMonotoneX)
    .x(function(d) { return x2(d.date); })
    .y0(height2)
    .y1(function(d) { return y2(d.price); });



  // make some buttons to drive our zoom
  d3.select("body").append("div")
    .attr("id","btnDiv")
    .style('font-size','75%')
    .style("width","250px")
    .style("position","absolute")
    .style("left","5%")
    .style("top","200px")

  var btns = d3.select("#btnDiv").selectAll("button").data([2001,2002,2003,2004])

  btns = btns.enter().append("button").style("display","inline-block")

  // fill the buttons with the year from the data assigned to them
  btns.each(function (d) {
    this.innerText = d;
  })

  btns.on("click",drawBrush);

  function drawBrush() {
    // define our brush extent to be begin and end of the year
    brush.extent([new Date(this.innerText + '-01-01'),new Date(this.innerText + '-12-31')])

    // Now draw the brush to match our extent
    // use transition to slow it down so we can see what is happening
    // remove transition so just d3.select(".brush") to just draw
    brush(d3.select(".brush").transition());

    // Now fire the brushstart,brushmove,and brushend events
    // remove transition so just d3.select(".brush") to just draw
    brush.event(d3.select(".brush").transition().delay(1000))
  }


  var svg = d3.select("body").append("svg")
      .attr("width",width + margin.left + margin.right)
      .attr("height",height + margin.top + margin.bottom);

  svg.append("defs").append("clipPath")
      .attr("id","clip")
    .append("rect")
      .attr("width",width)
      .attr("height",height);

  var focus = svg.append("g")
      .attr("class","focus")
      .attr("transform","translate(" + margin.left + "," + margin.top + ")");

  var context = svg.append("g")
      .attr("class","context")
      .attr("transform","translate(" + margin2.left + "," + margin2.top + ")");

  d3.csv("sp500.csv",type,function(error,data) {
  if (error) throw error;

  x.domain(d3.extent(data,function(d) { return d.date; }));
  y.domain([0,d3.max(data,function(d) { return d.price; })]);
  x2.domain(x.domain());
  y2.domain(y.domain());


    context.append("g")
        .attr("class","x brush")
        .call(brush)
      .selectAll("rect")
        .attr("y",-6)
        .attr("height",height2 + 7);
  });

  function brushed() {
    x.domain(brush.empty() ? x2.domain() : brush.extent());
  }

  function type(d) {
    d.date = parseDate(d.date);
    d.price = +d.price;
    return d;
  }
svg {
  font: 10px sans-serif;
}

.area {
  fill: steelblue;
  clip-path: url(#clip);
}

.axis path,.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.brush .extent {
  stroke: #fff;
  fill-opacity: .125;
  shape-rendering: crispEdges;
}
<!DOCTYPE html>
<Meta charset="utf-8">
<style>

svg {
  font: 10px sans-serif;
}

.area {
  fill: steelblue;
  clip-path: url(#clip);
}

.axis path,.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.brush .extent {
  stroke: #fff;
  fill-opacity: .125;
  shape-rendering: crispEdges;
}

</style>
<body>
<script src="http://d3js.org/d3.v4.js"></script>
</body>

请参阅fiddle以获取正确的错误.附加在代码段中时,错误会有所不同

任何帮助都非常值得赞赏.

更新:
错误是

d3.v4.js:12632 Uncaught TypeError: group.property is not a function

有没有人有一个预感是什么新的API来解决点击这个fiddle中的按钮的错误如果一个人可以更新它的小提琴将是很棒的.或者至少让我知道修改后的API,因为样本适用于v3.

解决方法

我在上述示例后遇到了同样的错误并找到了您的问题.由于您的小提琴不能正常工作(无法访问CSV),我无法确认我的答案是否适合您.但它在我本地工作.

它在v4上变得异常简单.只需调用brush.move(group,selection)以编程方式移动画笔选择.但是,参数选择似乎是基于画笔范围的相对坐标,因此如果您的轴是日期/时间,则可能必须将日期转换为坐标编号.

例如,我在定义画笔时传递了一个参数.

let width  = 200;
let height = 80;
let x      = d3.scaleTime().range([0,width]);
let brush  = d3.brushX()
    .extent([[0,0],[width,height]])
    .on("brush end",brushed);

context.append("g")
    .attr("class","brush")
    .call(brush)
    .call(brush.move,x.range());

然后我修改了drawBrush()函数,只使用了brush.move():

function drawBrush() {
    // Convert your dates to pixels along the brush's width.
    let start = x(new Date(this.innerText + '-01-01'));
    let end   = x(new Date(this.innerText + '-12-31'));

    // Alternatively,let's say the coordinates of your year is from 20% to 40% of your graph.
    // let start = 0.2 * width;
    // let end   = 0.4 * width;

    brush.move(context.select("g.brush").transition().delay(1000).duration(500),[start,end]);
}

不幸的是,这个解决方案将打破drawBrush()函数的两步转换,并将其合并为一个动画.您必须自己进行其他修改.

javascript – D3.js – 如何选择工作 – 需要澄清Mike的文章

javascript – D3.js – 如何选择工作 – 需要澄清Mike的文章

在 http://bost.ocks.org/mike/selection/,迈克谈到在选择上应用函数.

When you use a function to define a selection.attr or selection.style,the function is called for each element; the main difference with grouping is that the second argument to your function (i) is the within-group index rather than the within-selection index.

这可能很简单,但由于某种原因,我无法完全理解这一点.有人会善意用一个例子解释这个.

解决方法

the main difference with grouping is that the second argument to your
function (i) is the within-group index rather than the
within-selection index.

还记得传入d3中任何attr,style等函数的索引吗?

...
.attr('something',function(d,index) {
     // major gymnastics with d and index
}

因此,当您执行selectAll时,索引从每个组的0开始.

因此,如果您执行两个链式selectAlls,其中第一个(组)级别是行(tr),第二个(子级)级别是单元格(td),则您将传入以下作为2行x 3单元格的索引表

0,1,2,2

代替

0,3,4,5,6

当您使用单个selectAll仅选择6个节点时,这是您所期望的.

以下代码片段说明了这一点

d3.selectAll("#a tr").selectAll("td").text(function(d,index) {
      return index;
    })

     d3.selectAll("#b td").text(function(d,index) {
      return index;
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Grouped cells (i.e. 2 selectAll)
<table id="a">
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

Ungrouped cells (i.e. 1 selectAll)
<table id="b">
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

您链接到的页面上的第一个动画(http://bost.ocks.org/mike/selection/)很好地说明了这一点 – 这是相同的标记版本

今天关于javascript – 如何“转储”使用LinkedBrush插件为mpld3选择的点?的介绍到此结束,谢谢您的阅读,有关java – 使用LinkedHashMap实现LRU缓存、javascript onkeydown,onkeyup,onkeypress,onclick,ondblclick_javascript技巧、javascript – d3 v4实现中d3-brush的JS错误、javascript – D3.js – 如何选择工作 – 需要澄清Mike的文章等更多相关知识的信息可以在本站进行查询。

本文标签: