我试图在d3中创建一个简单的散点图(类似于matplotlib中的这个):
我使用xScale.domain(d3.extent(xvalues));
来设置比例的输入域范围。
extent()
使用这种方法会导致d3图中的某些点与轴重叠:
如何避免轴重叠并使边距类似于matplotlib的情节?
输入值有所不同,因此 /**
* getRandomWeightedElement()
* Utility function for getting random values with weighting.
* Pass in an associative array, such as array('A'=>5, 'B'=>45, 'C'=>50)
* An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.
* The return value is the array key, A, B, or C in this case. Note that the values assigned
* do not have to be percentages. The values are simply relative to each other. If one value
* weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%
* chance of being selected. Also note that weights should be integers.
*
* @param array $weightedValues
*/
function getRandomWeightedElement(array $weightedValues) {
$rand = mt_rand(1, (int) array_sum($weightedValues));
foreach ($weightedValues as $key => $value) {
$rand -= $value;
if ($rand <= 0) {
return $key;
}
}
}
输出的简单增量/减量看起来不像是一般解决方案。
答案 0 :(得分:2)
通常,处理此问题的最佳方法是调用scale的.nice()
函数,该函数将比例域的末端四舍五入为nice值。在您的特定情况下,这不起作用,因为值已经“很好”。
在这种情况下,我会计算域的范围并将其扩展一小部分。例如:
var padding = (xScale.domain()[1] - xScale.domain()[0]) / 10;
xScale.domain([xScale.domain()[0] - padding, xScale.domain()[1] + padding]).nice();
答案 1 :(得分:0)
在matplotlib图像中,点不重叠,x刻度具有负值。
在d3中:
var xScale = d3.scale.linear()
.domain([
d3.min(data, function(d) {
return d.val;
})-10, //so the domain is wider enough for the zero value
d3.max(data, function(d) {
return d.val;
}),
])
.range([height , 0])