What is the correct idiom to set a d3 linechart's x-axis labels to a human readable time?
By default the d3chart lineChart uses raw values for the x-axis, which results in epoch-millisecond labels. To convert to human readable in nvd3 one uses:
chart_obj.xAxis.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })
This translates to: splunkjs.mvc.Components.getInstance("chart_id").chart.xAxis.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); })
While this works from the console, putting it in the page source results in the console error: Cannot read property 'xAxis' of null
Hello unclethan,
There is some strangeness in the way the D3 chart gets created as compared to other controls. Essentially the behavior you are seeing is because we do not create the chart itself until it gets data. So it is available later when you are interacting with it from the console, but not from your page at creation time. The framework makes it possible to get around this by providing the D3 chart with a 'setup' function that will be run at the time the chart is created. Here you can set the various NVD3 options on the chart. So, for example, setting your tick format in the setup function would look something like:
var myChart = mvc.Components.getInstance("chart_id");
myChart.settings.set("setup", function(chart){
chart.xAxis.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); });
// other settings on chart
});
I hope that helps!
unclethan: can you post a sample query for which you don't get the axis ticks that you want? Ideally one that is on the _internal
index, so I can try it locally here.
In general, d3.axis does automatic tick placement and spacing - it will decide based on heuristics how many ticks to show and where to place them. You can override it using d3.axis.tickValues()
.
I'd like to get an end-to-end example with what you want though, so that we can iterate on it.
magnew_splunk: D3 is fine with setting the scale, the problem lies with D3. I take your answer to mean you don't know how to do it.
I find it odd that in splunk, wherein most of the data are time series, that a charting mechanism is supplied which does not handle time series data effectively.
The vagaries of D3 can be elusive. I would check out the NVD3 docs for more information about how to setup formatting: http://nvd3.org/
The Splunk d3 chart element uses NVD3 internally and formatting should be the same.
Thanks magnew_splunk.
As mentioned in my comment to my question, what I was attempting would only change the formatting of the tick label, not the spacing of the ticks, which is the desired result.
Do you know how to get properly spaced date-time ticks on the d3 graphs?
It turns out that the tickFormat would not work, as it would only change the formatting, and the tick placement.
How can I set up a time x-axis to set up ticks according to time - just like JSChart?