Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

javascript - D3: Create a grouped bar chart from json objects

I have some data like this:

[
 { id: 12, value1: "2.92", value2: "4.22", value3: "3.69" }
, 
 { id: 23, value1: "2.69", value2: "4.24", value3: "3.77" }
,
  ....
]

I want to create a horizontal grouped bar chart, so that there are 3 groups of bars, first all value1 bars (labeled as Value1), followed by all value2 bars and finally all value3 bars.

How can I do this - keeping in mind that the data will be updated dynamically in the future, so new data objects will be added and others will be removed. Guess I could use id as a key.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, supply or convert the data to an ordinary array or arrays eg

data = [ [ 2.92, 4.22, 3.69], [2.69, 4.24, 3.77] ]

Now you can use d3.transpose to pivot the data so you get

  var tdata = d3.transpose(data);

gives you

   [ [2.92, 2.69], [4.22, 4.24], [3.69, 3.77]]

then here is a group bar from iaindillingham to use as a model (I've fixed his version to use the latest d3 library). See it working here: http://bl.ocks.org/3532324


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...