2017-03-02 12 views
0

Ich versuche, den Monat und das Jahr Zecken von der x-Achse eines scaleTime zu entfernen, aber nicht wissen, ob es möglich ist:Anzeige nur wenige Tage auf scaleTime Zecken

xAxis of scaleTime

Ich habe versucht, die Methode tickFormat zu verwenden, aber ich kann nicht auf die Monats- und Jahreswerte zugreifen. Ich erhalte nur die erwarteten Ergebnisse, indem ich die Skalierung auf eine lineare Skalierung umstelle und die Werte manuell formatiere.

Es ist möglich, das erwartete Ergebnis mit einer Zeitskala zu erhalten?

const margin = { top: 20, right: 20, bottom: 20, left: 20 }; 
 
const width = 1000 - margin.top - margin.bottom; 
 
const height = 100 - margin.left - margin.right; 
 
const totalWidth = width + margin.top + margin.bottom; 
 
const totalHeight = height + margin.left + margin.right; 
 

 
let svg = d3.select('.chart') 
 
    .append('svg') 
 
    .attr('width', totalWidth) 
 
    .attr('height', totalHeight) 
 
    .append('g') 
 
    .attr('transform', `translate(${margin.left},${margin.top})`); 
 

 
let xScale = d3.scaleTime() 
 
    .rangeRound([0, width]) 
 
    .domain([ 
 
    new Date(1482883200000), // 2016-12-28 
 
    new Date(1485993600000) // 2017-02-02 
 
    ]); 
 

 
let xAxis = d3 
 
    .axisBottom(xScale); 
 

 
svg.call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script> 
 
<div class="chart"></div>

Antwort

1

Da ist es schwer zu wissen, wie die Achse Generator die Zecken für eine Zeitskala angezeigt wird, schlage ich vor, dass Sie die Zecken filtern, nachdem sie erstellt wurden:

Hier
d3.selectAll(".tick").each(function(d) { 
    if (d3.timeFormat("%Y")(d) == d3.select(this).text() || 
     d3.timeFormat("%B")(d) == d3.select(this).text()) { 
     d3.select(this).remove(); 
    } 
}) 

ist die Demo:

const totalWidth = 800; 
 
const totalHeight = 100; 
 

 
let svg = d3.select('body') 
 
    .append('svg') 
 
    .attr('width', totalWidth) 
 
    .attr('height', totalHeight); 
 

 
let xScale = d3.scaleTime() 
 
    .rangeRound([20, totalWidth - 20]) 
 
    .domain([ 
 
     new Date(1482883200000), // 2016-12-28 
 
     new Date(1485993600000) // 2017-02-02 
 
    ]); 
 

 
let xAxis = d3.axisBottom(xScale); 
 

 
svg.append("g").attr("transform", "translate(0,40)").call(xAxis); 
 

 
var format = d3.timeFormat("%a %d"); 
 

 
d3.selectAll(".tick").each(function(d) { 
 
    if (d3.timeFormat("%Y")(d) == d3.select(this).text() || d3.timeFormat("%B")(d) == d3.select(this).text()) { 
 
     d3.select(this).remove(); 
 
    } 
 
})
<script src="https://d3js.org/d3.v4.min.js"></script>