2017-02-23 99 views
1

我的要求是使用Plotly.js在X軸的特定日期繪製垂直線。我是情節新手,我設法找到一個選項,使用「形狀」選項繪製垂直線。使用Plotly.js的自定義垂直線

shapes:[{ 
       type: 'line', 
       x0: '2000-01-11', 
         y0:0, 
       x1: '2000-01-11', 
         y1:7,  
       line: { 
        color: 'grey', 
        width: 1.5, 
        dash:'dot' 
       } 
      }] 

但我面臨的主要困難是如何定義的Y軸值繪製垂直線時,爲Y軸刻度會有所不同基於數據。我希望它是動態的像y0:0; y1:(height-margin.top-margin.bottom)在我們用來繪製垂直線的d3中。

請幫助和代碼是在這裏 http://codepen.io/anon/pen/VpwWmV?editors=0010#0

回答

2

有一對夫婦的可能性,這可能爲你工作:

  • 使用yref: paper成爲獨立的Y軸比例的(所有值都歸一化爲0到1之間)
  • 總是畫到max imum和min imum y值

    y1: Math.min(...trace1.y), 
    
  • 採取相應的x值

    y1: trace1.y[trace1.x.indexOf('2000-01-02')], 
    

所有3種方法如下實現的y值。

var trace1 = { 
 
    x: ['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08', '2000-01-09', '2000-01-10', '2000-01-11', '2000-01-12', '2000-01-13', '2000-01-14', '2000-01-15', '2000-01-16', '2000-01-17', '2000-01-18', '2000-01-19', '2000-01-20', '2000-01-21', '2000-01-22', '2000-01-23', '2000-01-24', '2000-01-25', '2000-01-26', '2000-01-27', '2000-01-28', '2000-01-29', '2000-01-30', '2000-01-31'], 
 
    y: [4.3, 8.2, 4.1, 5.6, -3, -0.2, 0.3, 0.4, 4.1, 5, 4.6, -0.2, -8.5, -9.1, -2.7, -2.7, -17, -11.3, -5.5, -6.5, -16.9, -12, -6.1, -6.6, -7.9, -10.8, -14.8, -11, -4.4, -1.3, -1.1], 
 
    mode: 'lines', 
 
    type: 'scatter', 
 
    name: '2000' 
 
}; 
 

 
var data = [trace1]; 
 

 
var layout = { 
 
    xaxis: { 
 
    type: 'date', 
 
    title: 'January Weather' 
 
    }, 
 
    yaxis: { 
 
    title: 'Daily Mean Temperature' 
 
    }, 
 
    shapes: [{ 
 
    type: 'line', 
 
    x0: '2000-01-11', 
 
    y0: 0, 
 
    x1: '2000-01-11', 
 
    yref: 'paper', 
 
    y1: 1, 
 
    line: { 
 
     color: 'grey', 
 
     width: 1.5, 
 
     dash: 'dot' 
 
    } 
 
    }, { 
 
    type: 'line', 
 
    x0: '2000-01-17', 
 
    y0: 0, 
 
    x1: '2000-01-17', 
 
    y1: Math.min(...trace1.y), 
 
    line: { 
 
     color: 'grey', 
 
     width: 1.5, 
 
     dash: 'dot' 
 
    } 
 
    }, { 
 
    type: 'line', 
 
    x0: '2000-01-02', 
 
    y0: 0, 
 
    x1: '2000-01-02', 
 
    y1: trace1.y[trace1.x.indexOf('2000-01-02')], 
 
    line: { 
 
     color: 'grey', 
 
     width: 1.5, 
 
     dash: 'dot' 
 
    } 
 
    }], 
 
    title: '2000 Toronto January Weather' 
 
}; 
 

 
Plotly.plot('myDiv', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> 
 

 
<div id="myDiv" style="width:100%;height:400px;"></div>

+0

非常感謝。以上解決方案完美地按照我們的方式工作 – NewBie