简体   繁体   English

使用 Object 创建 D3 条形图

[英]Create a D3 Bar Chart Using a Object

I want to make a D3 bar chart using D3 v5.我想使用 D3 v5 制作 D3 条形图。 I can't seem to find this solution anywhere.我似乎在任何地方都找不到这个解决方案。 I want the bar height to be based on an object - that can dynamically change - rather than the an array in which D3 bar charts are normally based off of.我希望条形高度基于 object - 可以动态变化 - 而不是 D3 条形图通常基于的数组。 I have been able to append both axes with the proper data to an SVG but I cannot figure out how to append the bars to the SVG using the object. I have been able to append both axes with the proper data to an SVG but I cannot figure out how to append the bars to the SVG using the object.

For example, my object is例如,我的 object 是

let Obj = {
    red: 102,
    orange: 168,
    blue: 154,
    pink: 197
}

For my Axes, the y-axis is 0 to 200 (using D3.nice()) and the x-axis is red, orange, blue, pink.对于我的轴,y 轴是 0 到 200(使用 D3.nice()),x 轴是红色、橙色、蓝色、粉红色。

Any suggestions on how to append the bars appropriately?关于如何适当地 append 酒吧的任何建议?

Short answer: you can't.简短的回答:你不能。

D3 data() method accepts only three things: D3 data()方法只接受三件事:

  • An array 1 ;一个数组1 ;
  • A function; function;
  • Nothing.没有什么。

If you want to use an object as the data structure you'll have to bypass selecion.data() , but then there is no point in using D3 anymore, that is, you should create your dataviz using just plain Javascript.如果你想使用 object 作为数据结构,你必须绕过selecion.data() ,但是再使用 D3 就没有意义了,也就是说,你应该只使用普通的 Javascript 创建你的 dataviz。

If you still want to stick with D3, convert the object to an array:如果您仍想坚持使用 D3,请将 object 转换为数组:

 let Obj = { red: 102, orange: 168, blue: 154, pink: 197 }; const data = Object.entries(Obj).map(([key, value]) => ({ key: key, value: value })); console.log(data)


1: starting from D3 v6, the data method now accepts iterables such as TypedArray, NodeList, Map, Set etc. 1:从 D3 v6 开始, data方法现在接受诸如 TypedArray、NodeList、Map、Set 等可迭代对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM