Vega图表 - 如何使图表响应

时间:2018-06-05 14:26:19

标签: javascript charts responsive vega

我尝试使用Vega chart library创建一个简单的折线图。我的问题是我不能让它做出回应。我从他们提供的example开始,但我无法使图表相对于窗口大小进行维度。可能这不是Vega图表库的开箱即用功能。

你可以帮助我实现这个目标吗?或者您对如何创建基于屏幕大小自动调整大小的Vega图表有什么建议?

提前致谢!

更新: 以下是我到目前为止所做的更改:

window.onresize = function (event) {
  view.signal('width', event.target.innerWidth - 50)
      .signal('height', event.target.innerHeight - 50)
      .run('enter');
}

链接到小提琴:https://jsfiddle.net/TheoAbiel/ehtu6xkj/18/

这不是很好,我需要改进它。你有其他建议吗?

1 个答案:

答案 0 :(得分:1)

只要没有特定的交互依赖于原始视图维度中的数学运算,或者没有多个嵌套图表,此示例就应该有所帮助。

注意:规范中的autosize:{type:'fit',resize:true}有助于处理多个嵌套图,但会导致鼠标悬停时出现一些跳动行为,如本示例所示。

此代码段支持SVG和Canvas。还有两种规格可供选择。

运行下面的演示并调整浏览器的大小!响应度基于父元素,在这种情况下,父元素占主体的50%。请注意,DOM将在10秒后清除!

// const spec={$schema:'https://vega.github.io/schema/vega/v4.json',width:200,height:200,autosize:{type:'fit',resize:true,},signals:[{name:'startAngle',value:0,bind:{input:'range',min:0,max:6.29,step:0.01},},{name:'endAngle',value:6.29,bind:{input:'range',min:0,max:6.29,step:0.01},},{name:'padAngle',value:0,bind:{input:'range',min:0,max:0.1},},{name:'innerRadius',value:0,bind:{input:'range',min:0,max:90,step:1},},{name:'cornerRadius',value:0,bind:{input:'range',min:0,max:10,step:0.5},},{name:'sort',value:false,bind:{input:'checkbox'},},],data:[{name:'table',values:[{id:1,field:4},{id:2,field:6},{id:3,field:10},{id:4,field:3},{id:5,field:7},{id:6,field:8},],transform:[{type:'pie',field:'field',startAngle:{signal:'startAngle'},endAngle:{signal:'endAngle'},sort:{signal:'sort'},},],},],scales:[{name:'color',type:'ordinal',range:{scheme:'category20'}},],marks:[{type:'arc',from:{data:'table'},encode:{enter:{fill:{scale:'color',field:'id'},x:{signal:'width/2'},y:{signal:'height/2'},},update:{startAngle:{field:'startAngle'},endAngle:{field:'endAngle'},padAngle:{signal:'padAngle'},innerRadius:{signal:'innerRadius'},outerRadius:{signal:'width/2'},cornerRadius:{signal:'cornerRadius'},},},},],};

const spec={$schema:'https://vega.github.io/schema/vega/v4.json',width:400,height:200,autosize:{type:'fit',resize:true,},data:[{name:'table',values:[{category:'A',amount:28},{category:'B',amount:55},{category:'C',amount:43},{category:'D',amount:91},{category:'E',amount:81},{category:'F',amount:53},{category:'G',amount:19},{category:'H',amount:87},],},],signals:[{name:'tooltip',value:{},on:[{events:'rect:mouseover',update:'datum'},{events:'rect:mouseout',update:'{}'},],},],scales:[{name:'xscale',type:'band',domain:{data:'table',field:'category'},range:'width',padding:0.05,round:true,},{name:'yscale',domain:{data:'table',field:'amount'},nice:true,range:'height',},],axes:[{orient:'bottom',scale:'xscale'},{orient:'left',scale:'yscale'},],marks:[{type:'rect',from:{data:'table'},encode:{enter:{x:{scale:'xscale',field:'category'},width:{scale:'xscale',band:1},y:{scale:'yscale',field:'amount'},y2:{scale:'yscale',value:0},},update:{fill:{value:'steelblue'},},hover:{fill:{value:'red'},},},},{type:'text',encode:{enter:{align:{value:'center'},baseline:{value:'bottom'},fill:{value:'#333'},},update:{x:{scale:'xscale',signal:'tooltip.category',band:0.5},y:{scale:'yscale',signal:'tooltip.amount',offset:-2},text:{signal:'tooltip.amount'},fillOpacity:[{test:'datum===tooltip',value:0},{value:1},],},},},],};

// Vega object
const vegaDemo = {
  renderType: 'svg', // 'canvas',
  responsive: true,
  widthHeightRatio: spec.width / spec.height,
  wrapperElem: document.querySelector('#vega-view'),
};

// Create the view
vegaDemo.view = new vega.View(vega.parse(spec))
  .renderer(vegaDemo.renderType)
  .resize()
  .width(vegaDemo.wrapperElem.offsetWidth)
  .height(vegaDemo.wrapperElem.offsetWidth / vegaDemo.widthHeightRatio)
  .initialize(vegaDemo.wrapperElem)
  .run();

// If responsive
if (vegaDemo.responsive) {
  if (vegaDemo.renderType === 'canvas') {
    // For Canvas views
    vegaDemo.resize = () => {
      const width = vegaDemo.wrapperElem.offsetWidth;
      vegaDemo.view
      .width(width)
      .height(width / vegaDemo.widthHeightRatio)
      .run();
    };
    window.addEventListener('resize', vegaDemo.resize);
  } else {
    // For SVG views
    function responsive() {
      // Remove width/height attributes of Vega SVG and let viewBox handle the responsive behavior
      const viewDom = vegaDemo.wrapperElem.firstElementChild;
      viewDom.removeAttribute('width');
      viewDom.removeAttribute('height');
      viewDom.style.width = '100%';
    }
    responsive();
  }
}

// Destroy before changing your view on a SPA app
vegaDemo.destroy = () => {
  vegaDemo.view.finalize();
  if (vegaDemo.resize) {
    window.removeEventListener('resize', vegaDemo.resize);
  } else if (vegaDemo.responsive instanceof MutationObserver) {
    vegaDemo.responsive.disconnect();
  }
  vegaDemo.wrapperElem.innerHTML = ''; // Empty the wrapper if you aren't navigating away and simply want to remove the Vega view
};

// Destroy everything after 10 seconds
window.setTimeout(vegaDemo.destroy, 10000);
*,
*:before,
*:after {
  box-sizing: border-box;
}

article {
  width: 50%;
}
<!doctype html>
<html>
  <head>
    <title>Vega Responsive</title>
    <script src="https://cdn.jsdelivr.net/npm/vega@4.0.0-rc.3"></script>
  </head>
  <body>
    <p>Resize the browser!</p>
    <ul>
      <li>Specs taken from <a href="https://vega.github.io/vega/examples/" target="_blank">https://vega.github.io/vega/examples/</a>.</li>
      <li>This supports SVG &#38; Canvas (See the vegaDemo.renderType prop).</li>
      <li>This demo uses the wrapper's width...in this case, 50% of the body.</li>
      <li>The demo will be destroyed and removed after 10 seconds.</li>
    </ul>
    <article>
      <div id="vega-view"></div>
    </article>
  </body>
</html>

仅供参考:containerSizesignals中的事件相关也可以提供帮助。来自Banu Prakash的https://groups.google.com/forum/#!topic/vega-js/YovF3RvlnRg上的示例可能会有所帮助。