gpt4 book ai didi

javascript - 使用 Plottable.js 绘制基础数学 101 散点图

转载 作者:行者123 更新时间:2023-11-29 19:29:06 28 4
gpt4 key购买 nike

如何使用 Plottable.js 制作如下图所示的基本散点图? ?

  • 我的 JSON 有问题吗?
  • 如何显示减号?
  • 您还会做其他不同的事情吗?

样式无关紧要,默认的 Plottable.js 就可以了。

enter image description here

window.onload = function() {
var coordinates = [
{
x:"-5",
y:"3"
}, {
x:"2",
y:"-1,5"
}, {
x:"5",
y:"2,5"
}
];

var xScale = new Plottable.Scale.Linear();
var yScale = new Plottable.Scale.Linear();
var colorScale = new Plottable.Scale.Color("10");

var xAxis = new Plottable.Axis.Numeric(xScale, "bottom");
var yAxis = new Plottable.Axis.Numeric(yScale, "left");

var plot = new Plottable.Plot.Scatter(xScale, yScale)
.addDataset(coordinates)
.project("x", "", xScale)
.project("y", "", yScale)
.project("fill", "", colorScale);

var chart = new Plottable.Component.Table([
[yAxis, plot],
[null, xAxis]
]);

chart.renderTo("#my_chart");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="https://rawgit.com/palantir/plottable/develop/plottable.css">
</head>
<body>
<svg width="100%" height="600" id="my_chart"></svg>
<script src="https://rawgit.com/mbostock/d3/master/d3.min.js"></script>
<script src="https://rawgit.com/palantir/plottable/develop/plottable.min.js"></script>
</body>
</html>

最佳答案

Mark 的想法是正确的 - 表格系统本身不支持这种布局,因此您需要对它们的布局方式进行一些手动控制。然而,使用 Plottable API 中有些晦涩的部分,有一种更清晰、更受支持的方式来布置您想要的图表,并且不会出现轴稍微偏移的问题。

第一个变化是我们将完全停止使用表格布局引擎,因为它无法执行我们想要的操作。相反,我们会将所有组件放在一个 Component.Group 中。 Group 只是将组件叠加在同一空间中,根本不尝试定位它们。

var chart = new Plottable.Component.Group([yAxis, xAxis, plot]);

然后我们将使用 alignment and offset methods在基(抽象)组件类上定义的。我们将 y 轴的 x 对齐方式设置为“center”,将 x 轴的 y 对齐方式设置为“center”。这会将轴置于图表的中心。

var xAxis = new Plottable.Axis.Numeric(xScale, "bottom").yAlign("center");
var yAxis = new Plottable.Axis.Numeric(yScale, "left").xAlign("center");

我们在这一点上还没有完全完成,因为要真正使轴居中,我们需要将它们向后移动它们自身宽度的一半。宽度只在图表渲染时计算(严格来说是在 computeLayout 调用中,但那是内部细节),所以我们需要在图表渲染后设置一个偏移量:

chart.renderTo("#plottable");
xAxis.yOffset(xAxis.height()/2);
yAxis.xOffset(-yAxis.width()/2);

可以看到最终结果here (it's a fork of Mark's plnkr) .请注意,现在轴在图表的中心对齐,因为中心点完全位于 0,0。

关于javascript - 使用 Plottable.js 绘制基础数学 101 散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236117/

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