2014-09-20 51 views
3

我試圖做一個mpld3插件,所以當我將鼠標懸停在散點圖的圓上時,它顯示了sin行,但是x軸開始於行開始和結束行結束。mpld3插件設置xtics

我應該調用哪種方法來實現此目的?

import matplotlib 
import matplotlib.pyplot as plt 
import numpy as np 
import mpld3 
from mpld3 import plugins, utils 

mpld3.enable_notebook() 

class LinkedView(plugins.PluginBase): 
    """A simple plugin showing how multiple axes can be linked""" 

    JAVASCRIPT = """ 
    mpld3.register_plugin("linkedview", LinkedViewPlugin); 
    LinkedViewPlugin.prototype = Object.create(mpld3.Plugin.prototype); 
    LinkedViewPlugin.prototype.constructor = LinkedViewPlugin; 
    LinkedViewPlugin.prototype.requiredProps = ["idpts", "idline", "data"]; 
    LinkedViewPlugin.prototype.defaultProps = {} 
    function LinkedViewPlugin(fig, props){ 
     mpld3.Plugin.call(this, fig, props); 
    }; 

    LinkedViewPlugin.prototype.draw = function(){ 
     var pts = mpld3.get_element(this.props.idpts); 
     var line = mpld3.get_element(this.props.idline); 
     var data = this.props.data; 

     pts.elements().on("mouseover", function(d, i){ 

     var begin = d[0]-2; 
     var end = d[0]+2; 
     console.log("Show from " + begin + " to " + end); 
     var truncated = Array(); 
     for (var row = 0; row < data[i].length ; ++row){ 

      var x = data[i][row][0]; 
      if (begin <= x && x <= end){ 
       truncated.push(data[i][row]); 
      } 
     } 

     line.data = truncated; 
     line.elements().transition() 
      .attr("d", line.datafunc(line.data)) 
      .style("stroke", this.style.fill); 

     }); 
    }; 
    """ 

    def __init__(self, points, line, linedata): 
     if isinstance(points, matplotlib.lines.Line2D): 
      suffix = "pts" 
     else: 
      suffix = None 

     self.dict_ = {"type": "linkedview", 
         "idpts": utils.get_id(points, suffix), 
         "idline": utils.get_id(line), 
         "data": linedata} 

fig, ax = plt.subplots(2) 

# scatter periods and amplitudes 
np.random.seed(0) 
P =np.random.random(size=20)*10 
A = np.random.random(size=20) 
x = np.linspace(0, 10, 100) 
data = np.array([[x, Ai * np.sin(x/(Pi/10))] 

for (Ai, Pi) in zip(A, P)]) 
points = ax[1].scatter(P, A, c=(P/10 + A),s=200, alpha=0.5) 
ax[1].set_xlabel('Period') 
ax[1].set_ylabel('Amplitude') 

# create the line object 
lines = ax[0].plot(x, 0 * x, '-w', lw=3, alpha=0.5) 
ax[0].set_ylim(-1, 1) 

ax[0].set_title("Hover over points to see lines") 

# transpose line data and add plugin 
linedata = data.transpose(0, 2, 1).tolist() 
plugins.connect(fig, LinkedView(points, lines[0], linedata)) 

mpld3.display() 

回答

1

mpld3.js有一個javascript函數,叫做set_axlim。在您的JavaScript代碼中,您需要調用pts.ax.set_axlim,並設置您想要設置的限制。 Here是調用該方法的示例。

+0

謝謝你,真的很容易使你的幫助 「line.ax.set_axlim([begin,end],[ - 1,1]);」 – 2014-09-26 00:04:56