简体   繁体   中英

Create a D3 Bar Chart Using a Object

I want to make a D3 bar chart using D3 v5. 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. 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

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.

Any suggestions on how to append the bars appropriately?

Short answer: you can't.

D3 data() method accepts only three things:

  • An array 1 ;
  • A 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.

If you still want to stick with D3, convert the object to an array:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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