javascript - Styling axis text: is this the best (or only) way to do it? -
i want style axis date/time text make day breaks more prominent.
based on bunch of qas here came function below. working on timeline based on brush & zoom example calling function on every brush , zoom event.
the timeline still performant wondering if there more efficient way this. haven't been using d3
(or js, matter) long i'm still cobbling things without entirely understanding going on , possible ramifications may result.
function styleaxis() { d3.selectall('g.tick') .select('text') .style('fill', function (d) { var txt = d3.select(this).text().split(" "); var days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] if (days.indexof(txt[0]) != -1) { return "white" } else { return "gray" } }); }
result:
just save lines of code, can select text element inside tickformat
(despite not being purpose of tickformat
) using this
, when define line generator, , apply style want:
var axis = d3.axisbottom(scale) .tickformat(function(d) { if (d === "bar") { d3.select(this).style("fill", "gray") } return d; });
here demo:
var svg = d3.select("svg") var scale = d3.scaleband() .range([20, 280]) .domain(["foo", "bar", "baz"]); var axis = d3.axisbottom(scale) .tickformat(function(d) { if (d === "bar") { d3.select(this).style("fill", "gray") } return d; }); var gx = svg.append("g") .attr("transform", "translate(0,50)"); axis(gx);
<script src="https://d3js.org/d3.v4.min.js"></script> <svg></svg>
in example, style depends on data. on other hand, if style doesn't depend on data (for instance, when want apply same style ticks), alternative shorter: apply style containing <g>
element.
therefore, approach not one. regarding being best 1 prefer not saying anything, since opinion based , depends on several factors.
Comments
Post a Comment