I'm using lineChart from Rcharts nvd3, and I'd like to format the y values as a percent precise to one tenth of a %. I can format as a percent as below, but when I hover over the points, it only shows a % precise to 1%, I can't get it to be precise to the tenth decimal place.
p$yAxis(tickFormat = "#!
function(d) {return d3.format('%')(d)}
!#"
)
I tried doing this, but didn't work:
p$yAxis(tickFormat = "#!
function(d) {return d3.format('.0%')(d)}
!#"
)
Try:
p$yAxis(tickFormat = "#!
function(d) {return d3.format('.1%')(d)}
!#"
)
From the d3 wiki:
The precision indicates how many digits should be displayed after the decimal point for a value formatted with types "f" and "%"
Related
I'm using d3js v5, with an Ordinal scale for my X axis on a line chart.
this.x = scaleOrdinal()
.domain(axisXDataTruncated.labels)
.range(axisXDataTruncated.range);
When I draw my x axis using this:
this.root
.append('g')
.attr('class', 'x axis')
.attr('transform', `translate(0, ${this.height})`)
.call(
axisBottom(this.x).tickFormat((data: string | number) =>
formatter(
this.graphDataMerged.lineChartOptions.axis.x.format,
data,
this.graphDataMerged.lineChartOptions.axis.x.currency
)
)
);
I'm using string labels (['Week 1'. 'Week 2',... 'Week 26'] as labels.
When I have a long number of labels, the x axis, discards the last labels and crops to a certain value. For example, with 26 values. Tha last label shows as 25, which is shown at the very end of the x axis.
Because the dots and lines of my chart includes the value at position 26, the axis and the dots don't match.
If I expand the browser's width, the last value of the x axis magically appears.
What could I be doing wrong? Is it a bug in v5?
I made a histogram / bar graph. I read in my frequency data as integers and set up my y-axis like this:
var yScale = d3.scale.linear().range([300, 0]).domain([0, 2]);
var yAxis = d3.svg.axis().scale(yScale).orient(‘left’)
.tickFormat(d3.format(,.0f));
Unfortunately, the y axis repeats each frequency several times as shown here:
How do I tell d3 to stop repeating y-values on the y-axis? I don’t want to use .ticks(someNumber) since I want to keep the number of ticks itself flexible.
I needed mine to be dynamic, this worked for me: [Version 4]
var y = d3.scaleLinear().range([height, 0]);
var yAxis = d3.axisLeft()
.scale(y)
.tickFormat(d3.format("%d"));
// Reset the axes domains with new data
y.domain([0, d3.max(data, function (d) { return d.value; })]);
if (y.domain() [1] < 10) {
yAxis.ticks(y.domain()[1])
// 2 ticks
//yAxis.tickValues(y.domain());
}
// Add the y-axis with a transition
yAxisG
.transition()
.duration(500)
.call(yAxis);
Use .ticks(n) instead of tickFormat() on your axis. The ticks() function defines how many ticks d3 should target - it's not always exactly that number. It chooses the most sane division unit on its own. n is 10 by default but you could change it depending on the domain, so for the example data you could set it to 3 (0,1,2). You could theoretically also use it on data enter.
Is your graph's range/height dynamic depending on data? In most cases you don't want that as it's unpredictable. And if you set your graph's height explicitly anyway you DO want to limit the number of ticks and labels to a number best suiting that size.
You might also want to look into https://github.com/mbostock/d3/wiki/Quantitative-Scales#linear_nice . That allows you to define rules for your ticks.
I'm currently working on a quite basic graph using 2 ordinal axes. X axis shows 4 categories, Y axis shows 3. For some reason, the plotted circles don't align with the plotted axes.
An example can be seen at http://jsfiddle.net/SrdY6/. Problem seems to be translation-related, but the only translation in there is applied to the large containing <g> element:
var lunchgraph = svg.append("g")
.attr("class", "lunchgraph")
.attr("transform", "translate(" + lunchmargin.left + "," + lunchmargin.top + ")");
I've been looking at this for some time now, but can't spot where things go wrong... Anyone with more insight?
Nothing like putting a question out there and risking public shame, only to find out the answer within minutes after posting.
For ordinal axes configured with rangeBands or rangeRoundBands, the scale function returns the lower value of the given input. To have the plot align with the exact categorical labels, you need to add half of the rangeBand to the calculated coordinate.
So: no problem with the translations or anything, but with the computation of cx and cy coordinates for placing the circles in the graph.
Correct code:
.attr("cx", function(d) { return x(d.label) + x.rangeBand()/2 ;} )
.attr("cy", function(d) { return y(d.sqid) + y.rangeBand()/2 ; } )
According to the d3 docs:
When interpolating to or from zero, some interpolated values may be very small. JavaScript formats small numbers in exponential notation, which unfortunately is not supported by CSS. For example, when transitioning opacity to fade in or out, the number 0.0000001 is converted to the string "1e-7" and then ignored, giving the default value of 1! To avoid distracting flicker, start or end the transition at 1e-6 rather than 0; this is the smallest value not formatted in exponential notation.
This is giving me a problem with a histogram which has some very low frequencies. The rectangle height is interpolated as a scientific number which throws an error. I've tried the following:
svg.selectAll(".bar")
.data(freq)
.filter(function(d) {return d.freq>0.005})
.transition()
.duration(1000)
.attr("y", function(d) { return y(d.freq); })
.attr("height", function(d) { return height - y(d.freq) })
This avoids the end value being zero - but how do I filter out those elements where the initial value may be close to zero?
You can do the same thing when you're creating the bars, i.e.
svg.selectAll("rect").data(freq).filter(...)
.enter().append("rect");
At this point, it would actually make sense to prefilter your data before passing it to D3 at all, i.e. use something like var filteredData = data.filter(...) and use filteredData.
I've got a dataset I'm graphing with d3.js. The x axis represents time (in minutes). I'd like to display this axis in an hh:mm format, and I can't find a way to do this cleanly within d3.
My axis code looks like:
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(d3.svg.axis()
.scale(x)
.orient('bottom'));
Which generates labels in minutes that looks like [100, 115, 130, 140], etc.
My current solution is to select the text elements after they've been generated, and override them with a function:
svg.selectAll('.x.axis text')
.text(function(d) {
d = d.toFixed();
var hours = Math.floor(d / 60);
var minutes = pad((d % 60), 2);
return hours + ":" + minutes;
});
This outputs axis ticks like [1:40, 1:55, 2:10], etc.
But this feels janky and avoids the use of d3.format. Is there a better way to make these labels?
If you have absolute time, you probably want to convert your x data to JavaScript Date objects rather than simple numbers, and then you want to use d3.time.scale and d3.time.format. An example of "hh:mm" format for an axis would be:
d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%H:%M"));
And actually, you may not need to specify a tick format at all; depending on the domain of your scale and the number of ticks, the default time scale format might be sufficient for your needs. Alternatively, if you want complete control, you can also specify the tick intervals to the scale. For example, for ticks every fifteen minutes, you might say:
d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(d3.time.minutes, 15)
.tickFormat(d3.time.format("%H:%M"));
If you have relative time, i.e. durations, (and hence have numbers representing minutes rather than absolute dates), you can format these as dates by picking an arbitrary epoch and converting on-the-fly. That way you can leave the data itself as numbers. For example:
var formatTime = d3.time.format("%H:%M"),
formatMinutes = function(d) { return formatTime(new Date(2012, 0, 1, 0, d)); };
Since only the minutes and hours will be displayed, it doesn't matter what epoch you pick. Here’s an example using this technique to format a distribution of durations:
http://bl.ocks.org/3048166