I have a project where I am attempting to implement a dc.js composite chart along with a bar chart and brush chart. The composite chart displays with a y scale from 0 - 50 but all of my data points fall within 49.5 - 50.25 so the line looks very flat. I would like to set the scale to my min/max data +/- 1. Here is the code I am using:
var cf = crossfilter(data);
var dim = cf.dimension(function (d) { return +d.trend; }),
grp = dim.group().reduceCount(),
min = dim.bottom(1)[0].trend,
max = dim.top(1)[0].trend;
console.log(min); // min is 49.684
console.log(max); // max is 50.272
compositeChart.width(w)
.height(h)
...
.y(d3.scale.linear().domain([min, max]))
...
.dimension(dim)
.group(grp)
.yAxis().tickFormat(function (d) { return d3.format(',.1f)(d); });
dc.renderAll();
When the chart is rendered I still have a Y Axis scale from 0 - 50?? I also tried hard coding the min and max and it still does not change the scale..
Any suggestions are appreciated!
Related
I'm newbie with D3 and I'm trying to set plots in a graphic where x Axis has labels.
I set the points, but not correctly over the line of each x label. You can check it on this image:
You can find the code in codesandbox:
The file where I define the Scatter Plot is: MultipleScatterPlot.js
What am I doing wrong?
Fixed: I have fixed my problem using the method padding(1)
/**
* Method which serves us to define the scale and range of the graphics
* #param {*} data
*/
setScales(data) {
let xRange = [
this.state.OFFSET_LEFT,
this.state.WIDTH - this.state.OFFSET_RIGHT
];
let yRange = [
this.state.OFFSET_TOP,
this.state.HEIGHT - this.state.OFFSET_BOTTOM
]; // flip order because y-axis origin is upper LEFT
let xScale = d3
.scaleBand()
.domain(
data.map(d => {
return d.value_x;
})
)
.range(xRange)
.padding(1);
let yScale = d3
.scaleLinear()
.domain([100, 0])
.range(yRange);
return {
xScale: xScale,
yScale: yScale,
xRange: xRange,
yRange: yRange
};
}
Is hire when if we add padding(1) all points are setted to their correspondiente x_label, like you can see now:
And now, is perfect!!! It's what I want to do!!!
I'm new to d3 and have the following code for creating the x-axis on my graph:
export const drawXAxis = (svg, timestamps, chartWidth, chartHeight) => {
console.log(chartWidth); // 885
console.log(timestamps.length); // 310
const xScale = d3.scaleLinear()
.domain([-1, timestamps.length])
.range([0, chartWidth]);
const xBand = d3.scaleBand()
.domain(
d3.range(-1, timestamps.length))
.range([0, chartWidth])
.padding(0.3);
const xAxis = d3.axisBottom()
.scale(xScale)
.tickFormat(function(d) {
const ts = moment.utc(timestamps[d]);
return ts.format('HH') + 'h';
});
const gX = svg.append("g")
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + chartHeight + ")")
.call(xAxis);
return [xScale, xBand, xAxis, gX];
};
As I understand it, d3 decides on the number of ticks that appears on the X-axis.
In order to gain more control over the values appearing on the X-axis for zooming purposes, I would like to understand how d3 determines that - in this case - I have 16 ticks.
What If I want to space the ticks more evenly, for example, I want to see a tick on every 12 or 6 hours? My data contains 0 -> 23 hour values per day consistently, but d3 displays random hours on my graph.
I'm gonna answer just the question in the title ("how is the number of ticks on an axis defined?"), not the one you made at the end ("What If I want to space the ticks more evenly, for example, I want to see a tick on every 12 or 6 hours?"), which is not related and quite simple to fix (and, besides that, it's certainly a duplicate).
Your question demands a detective work. Our journey starts, of course, at d3.axisBottom(). If you look at the source code, you'll see that the number of ticks in the enter selection...
tick = selection.selectAll(".tick").data(values, scale).order()
...depends on values, which is:
var values = tickValues == null ? (scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) : tickValues
What this line tells us is that, if tickValues is null (no tickValues used), the code should use scale.ticks for scales that have a ticks method (continuous), our just the scale's domain for ordinal scales.
That leads us to the continuous scales. There, using a linear scale (which is the one you're using), we can see at the source code that scale.ticks returns this:
scale.ticks = function(count) {
var d = domain();
return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
};
However, since ticks is imported from d3.array, we have to go there for seeing how the ticks are calculated. Also, since we didn't pass anything as count, count defaults to 10.
So, finally, we arrive at this:
start = Math.ceil(start / step);
stop = Math.floor(stop / step);
ticks = new Array(n = Math.ceil(stop - start + 1));
while (++i < n) ticks[i] = (start + i) * step;
Or this:
start = Math.floor(start * step);
stop = Math.ceil(stop * step);
ticks = new Array(n = Math.ceil(start - stop + 1));
while (++i < n) ticks[i] = (start - i) / step;
Depending on the value of steps. If you look at the tickIncrement function below, you can see that steps can only be 1, 2, 5 or 10 (and their negatives).
And that's all you need to know the length of the array in the variable ticks above. Depending on the start and stop values (i.e., depending on the domain), sometimes we have more than 10 ticks (16 in your case), sometimes we have less than 10, even if the default count is 10. Have a look here:
const s = d3.scaleLinear();
console.log(s.domain([1,12]).ticks().length);
console.log(s.domain([100,240]).ticks().length);
console.log(s.domain([10,10]).ticks().length);
console.log(s.domain([2,10]).ticks().length);
console.log(s.domain([1,4]).ticks().length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
The last example, as you can see, gives us 16 ticks.
plotly.js 2D histograms and contour plots automatically generate a z-axis range that accommodates the entire range of z values in the dataset being plotted. This is fine to start, but when I click-and-drag on the plot to zoom in, I'd like the z axis range to also zoom in to accommodate only the range of z values currently on display; instead, the z axis never changes. Here's a codepen (forked from the plotly examples, thanks plotly) to play around with: http://codepen.io/anon/pen/MKGyJP
(codepen code inline:
var x = [];
var y = [];
for (var i = 0; i < 500; i ++) {
x[i] = Math.random();
y[i] = Math.random() + 1;
}
var data = [
{
x: x,
y: y,
type: 'histogram2d'
}
];
Plotly.newPlot('myDiv', data);
)
This seems like pretty conventional behavior - am I missing an option in the docs somewhere to do this?
If there's no built-in option to do this, an acceptable alternative solution would be to manually set new z limits in a zoom callback, which is easy enough to implement per this example: http://codepen.io/plotly/pen/dogexw - in which case my question becomes, is there a convenience method to get the min and max z currently on display?
Thanks in advance,
plotly.js doesn't have a zoom-specific callback at the moment(follow this issue for updates).
One alternative would be to add a mode bar button updating the colorscale range:
Plotly.newPlot('myDiv', data, {}, {
modeBarButtonsToAdd: [{
name: 'click here to update the colorscale range',
click: function(graphData) {
var xRange = graphData.layout.xaxis.range,
yRange = graphData.layout.yaxis.range;
var zMin, zMax;
// code that would compute the colorscale range
// given xRange and yRange
// for example given these values:
zMin = 10;
zMax = 20;
Plotly.restyle('myDiv', {zmin: zMin, zmax: zMax});
}
}]
});
Complete example: http://codepen.io/etpinard/pen/JGvNjV
I am working on a chart looking like this now:
I use d3 scales and ranges to setup sizes and coordinates of circles, from JSON data.
All works fine but I need to make sure those circles that are close to extreme values don't overlap the sides of the chart (like orange circle on the top right and blue one on the bottom side), so I think I need to play with ranges and change coordinates in case they overlap or is there a better tried way to do this?
When drawing circles, in addition to the x and y scaling functions we also use an r scaling function:
var rScale = d3.scale.linear()
.domain([0, maxR])
.range([0, maxBubbleRadius]);
var xScale = d3.scale.linear()
.domain([minX, maxX])
.range([0, chartWidth]);
var yScale = d3.scale.linear()
.domain([minY, maxY])
.range([chartHeight, 0]);
where maxR is the largest r value in your dataset and maxBubbleRadius is however large you want the largest circle to be, when you plot it.
Using the x and y scaling functions it is easy to calculate where the centre of each circle will be plotted, we can then add on the (scaled) r value to see if the circle will spill over a chart boundary. With a scenario like the first chart below we can see that 4 of the circles spill over. The first step to remedy this is to find out how many vertical and horizontal units we spill over by and then increase the minimum and maximum x and y values to take this into account, before recalculating the xScale and yScale vars. If we were to then plot the chart again, the boundary would move out but there would probably still be some visible spillage (depending on actual values used); this is because the radius for a given circle is a fixed number of pixels and will therefore take up a different number of x and y units on the chart, from when we initially calculated how much it spilled over. We therefore need to take an iterative approach and keep applying the above logic until we get to where we want to be.
The code below shows how I iteratively achieve an acceptable scaling factor so that all the circles will plot without spilling. Note that I do this 10 times (as seen in the loop) - I've just found that this number works well for all the data that I've plotted so far. Ideally though, I should calculate a delta (the amount of spillage) and iterate until it is zero (this would also require overshooting on the first iteration, else we'd never reach our solution!).
updateXYScalesBasedOnBubbleEdges = function() {
var bubbleEdgePixels = [];
// find out where the edges of each bubble will be, in terms of pixels
for (var i = 0; i < dataLength; i++) {
var rPixels = rScale(_data[i].r),
rInTermsOfX = Math.abs(minX - xScale.invert(rPixels)),
rInTermsOfY = Math.abs(maxY - yScale.invert(rPixels));
var upperPixelsY = _data[i].y + rInTermsOfY;
var lowerPixelsY = _data[i].y - rInTermsOfY;
var upperPixelsX = _data[i].x + rInTermsOfX;
var lowerPixelsX = _data[i].x - rInTermsOfX;
bubbleEdgePixels.push({
highX: upperPixelsX,
highY: upperPixelsY,
lowX: lowerPixelsX,
lowY: lowerPixelsY
});
}
var minEdgeX = d3.min(bubbleEdgePixels, function(d) {
return d.lowX;
});
var maxEdgeX = d3.max(bubbleEdgePixels, function(d) {
return d.highX;
});
var minEdgeY = d3.min(bubbleEdgePixels, function(d) {
return d.lowY;
});
var maxEdgeY = d3.max(bubbleEdgePixels, function(d) {
return d.highY;
});
maxY = maxEdgeY;
minY = minEdgeY;
maxX = maxEdgeX;
minX = minEdgeX;
// redefine the X Y scaling functions, now that we have this new information
xScale = d3.scale.linear()
.domain([minX, maxX])
.range([0, chartWidth]);
yScale = d3.scale.linear()
.domain([minY, maxY])
.range([chartHeight, 0]);
};
// TODO: break if delta is small, rather than a specific number of interations
for (var scaleCount = 0; scaleCount < 10; scaleCount++) {
updateXYScalesBasedOnBubbleEdges();
}
}
I'm trying to draw a line using D3.js. They are samples taken at intervals over a period of time. I want to draw them with a time axis for x. Each point of data is just an index in an array and I can't figure out how to set up my axis in such a way that I don't have to manually re-scale the axis before calling d3.time.scale.
Does anyone know how to clean up the scale?
Snippets out of my code. My actual code downloads the data and draws a lot of lines over different time periods with different offsets translated in the graph.
// input data
var start_time = 1352684763;
var end_time = 1352771163;
// data is exactly 100 samples taken between start_time and end_time
var data = [140,141,140,140,139,140,140,140,140,141,139,140,54,0,0,0,0,0,0,0,0,0...]
var y_max = d3.max(data);
// graph
var scale_x = d3.time.scale().domain([start_time, end_time]).range([0, 100]);
var scale_y = d3.scale.linear().domain([0, y_max]).range([height, 0]);
var step = (end_time - start_time)/100;
function re_scale(x) { return start_time + x*step; }
// for x, rescale i (0..99) into a timestamp between start_time and end_time before returning it and letting scale_x scale it to a local position. Awkward.
var line = d3.svg.line()
.x(function(d, i) { return scale_x(re_scale(i)); })
.y(scale_y)
.interpolate('basis')
var g = graph.selectAll("g")
.append('svg:path')
.attr('d', function(d) { return line(data); })
// also draw axis here...
The "domain" should refer to the span in the data, and the "range" should refer to the span on the screen.
At the moment it would be interpreting .range([0, 100]) on scale_x as a number of pixels. If you change this to .range([0, width]) it should work without needing to re-scale.
d3.time.scale() only needs to know the start and end points to produce a good axis. However if you do want a tick for every data point there are options do do this in the docs.