简体   繁体   中英

Javascript / D3 — Conditional Format for Label

I have a heatmap calendar that contains hours broken into values like: 6,30,7,30,8,30. So, you can assume 6 is 6:00, and the 30 after is 6:30. I want the hour values to be larger (say 12px) and the 30 to be the default I have in CSS (say 10px). Here is the javascript I have already for plotting the hour labels:

Set up the colors, days, hours

 var margin = { top: 20, right: 0, bottom: 120, left: 30 },
          width = 1080 - margin.left - margin.right,
          height = 430 - margin.top - margin.bottom,
          gridSize = Math.floor(width / 28),
          legendElementWidth = gridSize*2,
          buckets = 9,
          colors = ["#f03b20","#fd8d3c","#feb24c","#fed976","#ffffb2","#c2e699","#78c679","#31a354","#006837"], //,"#081d58"], // alternatively colorbrewer.YlGnBu[9]
          days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
          times = ["6", "30", "7", "30", "8", "30", "9", "30", "10", "30", "11", "30", "12", "30", "1", "30", "2", "30", "3", "30", "4", "30", "5", "30","6","30","7","30"];

Plot the x-axis labels.

var timeLabels = svg.selectAll(".timeLabel")
              .data(times)
              .enter().append("text")
                .text(function(d) { return d; })
                .attr("x", function(d, i) { return i * gridSize; })
                .attr("y", 0)
                .style("text-anchor", "middle")
                .attr("transform", "translate(" + gridSize / 2 + ", -6)")
                .attr("class", function(d, i) { return ((i >= 7 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });*

My question: How can I modify this Javascript to have a conditional format so that the hour numbers (1-12) have a larger font and the 30 uses the default?

You can pass a function to set the font-size attribute:

.attr("font-size", function(d) { return +d < 20 ? "12px" : "10px"; });

In general, it would be more D3-like to use a time scale and axis to have it format and place the labels automatically. That would make what you want to do more difficult though, so it may be better for you to stick with what you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM