23

D3.js で散布図を描画する方法の例を探しています。

公式の D3.jsの例を調べても、単純な例を見つけることができませんでした(印象的ではありますが)。次の方法を知りたいだけです。

  • x 軸と y 軸を描画してラベルを付ける
  • グラフ上に散布点を描画します。

この例はこのD3 再利用可能ライブラリで見つけましたが、必要以上に複雑で、外部ファイルがあり、重要なポイントを引き出すのが困難です。簡単な散布図の例を教えてもらえますか?

どうもありがとう。

4

3 に答える 3

26

これで始められるはずです。http://bl.ocks.org/2595950で実際の動作を確認できます。

// data that you want to plot, I've used separate arrays for x and y values
var xdata = [5, 10, 15, 20],
    ydata = [3, 17, 4, 6];

// size and margins for the chart
var margin = {top: 20, right: 15, bottom: 60, left: 60}
  , width = 960 - margin.left - margin.right
  , height = 500 - margin.top - margin.bottom;

// x and y scales, I've used linear here but there are other options
// the scales translate data values to pixel values for you
var x = d3.scale.linear()
          .domain([0, d3.max(xdata)])  // the range of the values to plot
          .range([ 0, width ]);        // the pixel range of the x-axis

var y = d3.scale.linear()
          .domain([0, d3.max(ydata)])
          .range([ height, 0 ]);

// the chart object, includes all margins
var chart = d3.select('body')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')

// the main object where the chart and axis will be drawn
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')   

// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');

main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');

main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);

// draw the graph object
var g = main.append("svg:g"); 

g.selectAll("scatter-dots")
  .data(ydata)  // using the values in the ydata array
  .enter().append("svg:circle")  // create a new circle for each value
      .attr("cy", function (d) { return y(d); } ) // translate y value to a pixel
      .attr("cx", function (d,i) { return x(xdata[i]); } ) // translate x value
      .attr("r", 10) // radius of circle
      .style("opacity", 0.6); // opacity of circle

このように使用されます:

<!DOCTYPE html>
<html>
  <head>
    <title>The d3 test</title>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.v2.js" charset="utf-8"></script>
  </head>
  <body>
    <div class='content'>
      <!-- /the chart goes here -->
    </div>
    <script type="text/javascript" src="scatterchart.js"></script>
  </body>
</html
于 2012-05-04T05:06:20.817 に答える
1

NVD3.js には素晴らしい例があります。ライブラリも含めるか、実装を確認する必要があります。この散布図の例を見てみましょう: http://nvd3.org/livecode/#codemirrorNav

于 2012-12-29T20:17:56.157 に答える
0

C3.js (D3 ベース) を使用した散布図の例をご覧ください: http://c3js.org/samples/chart_scatter.html

次のように半径のサイズを変更できます:

于 2015-04-13T06:46:05.167 に答える