gpt4 book ai didi

javascript - D3.js 中的简单散点图示例?

转载 作者:行者123 更新时间:2023-12-03 02:48:31 27 4
gpt4 key购买 nike

我正在寻找如何在 D3.js 中绘制散点图的示例。

通过查看official D3.js examples我还没有找到一个简单的例子。 (尽管它们令人印象深刻)。我只是想知道如何:

  • 绘制并标记 x 轴和 y 轴
  • 在图表上绘制散点。

我确实找到了this example在这个D3 reusable library ,但它比我需要的要复杂得多,外部文件使得很难提取要点。谁能指点我一个简单的散点图示例来开始使用?

非常感谢。

最佳答案

这应该可以帮助您入门。您可以在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

关于javascript - D3.js 中的简单散点图示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10440646/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com