根据数据有条件地填充多个svg

时间:2018-09-04 07:22:31

标签: javascript d3.js

在下面的代码中,我有两年的日历,两个用户在每个日历上显示相同的年份。

在以下代码中,我完成了条件填充检查,检查日期是否为周末并将其填充为灰色,效果很好。

    .attr("fill", function(d) {
        var value = new Date(d).getDay();
        var check = (value === 6 || value === 0) // Check if weekend
        if (check) return "#E0E0E0"
        else return "none"; 
    });

我现在想做的是,如果提供了某个日期,则用红色正方形填充,例如:

if (d == "2018-10-12") return "red"

这里的问题是,由于两个日历都有该日期,因此显然将两个日历都填充为红色。

我不确定如何将日期与每个svg的数据数组进行比较,这是我想将日期与之比较的测试数据。

var data = [
    {id: "Some_Name", dates: ["2018-01-01", "2018-02-11"]},    // <-- svg1
    {id: "Another_Name", dates: ["2018-03-01", "2018-04-11"]}, // <-- svg2
]

上面的数据段是任意的,如果您具有其他数据结构,甚至只是一个字符串(将每个svg与之比较),那么也可以。

这是所有代码:

var formatDay = d3.timeFormat("%d");
var formatDate = d3.timeFormat("%Y-%m-%d");

var data = [
	{id: "Some_Name", dates: ["2018-01-01", "2018-02-11"]},
	{id: "Another_Name", dates: ["2018-03-01", "2018-04-11"]},
]

var width = 1000,
	height = 196,
	cellSize = 18,
	transCell1 = ((width - cellSize * 53) / 2),
	transCell2 = (height - cellSize * 7 - 1);

var currentYear = new Date().getFullYear()

var id = [...new Set(data.map(function(d) {
	return d.id
}))];

var svg = d3.select("#calendars").selectAll("svg")
	.data(id)
.enter().append("svg")
	.attr("class", "myCalendar")
	.attr("id", d => d)
	.attr("width", width)
	.attr("height", height)
.append("g")
	.attr("transform", 
		"translate(" + transCell1 + "," + transCell2 +")");

var names = svg.append("text")
	.attr("dx", - 5)
	.attr("dy", - 35)
	.attr("font-size", 14)
	.attr("text-anchor", "start")
	.text(function(d) {
		var value = d.split("_")
		return value[0] + " " + value[1]
	});

update(currentYear, id);

function update(year, user) {

	var getDays = function() { 
			return d3.timeDays(
				new Date(year, 0, 1), new Date(year + 1, 0, 1)
			);
		}

	var fillDays = svg.selectAll(".fillDays")
		.data(getDays)

	fillDays.exit().remove()

	fillDays = fillDays
	.enter().append("rect")
		.attr("class", "fillDays")
		.attr("stroke", "#ccc")
		.attr("width", cellSize)
		.attr("height", cellSize)
		.merge(fillDays)
		.attr("x", function(d) { 
			return d3.timeWeek.count(d3.timeYear(d), d) * cellSize;
		})
		.attr("y", function(d) { return d.getDay() * cellSize; })
		.datum(d3.timeFormat("%Y-%m-%d"))
		.attr("fill", function(d) {
			var value = new Date(d).getDay();
			var check = (value === 6 || value === 0) // Check if weekend
			if (check) return "#E0E0E0"
			if (d == data[0].dates[0]) return "red" // 
			else return "none"; 
		});

	var days = svg.selectAll(".days")
		.data(getDays)

	days = days
	.enter().append("text")
		.attr("class", "days")
		.attr("font-size", 11)
		.attr("dy", 13)
		.attr("dx", 3)
		.style("pointer-events", "none")
		.attr("fill", "#333")
		.attr("stroke", "none")
		.merge(days)
		.attr("x", function(d) {
			return d3.timeWeek.count(d3.timeYear(d), d) * cellSize;
		})
		.attr("y", function(d) { return d.getDay() * cellSize; })
		.text(function(d) {
			return formatDay(d)
		})
	
	var lines = svg.selectAll("path")
		.data(function() { 
			return d3.timeMonths(
				new Date(year, 0, 1), new Date(year + 1, 0, 1)
			); 
		})

	lines.exit().remove()

	lines = lines
	.enter().append("path")
		.attr("fill", "none")
		.attr("stroke", "#000")
		.merge(lines)
		.attr("d", pathMonth);

	//
	// Hardcoded text
	//

	var months = svg.selectAll(".months")
		.data([
			"Jan", "Feb", "Mar", "Apr", "Maj", "Jun", 
			"Jul", "Aug", "Sep", "Okt", "Nov", "Dec"])

	months = months
		.enter()
	.append("text")
		.attr("class", "months")
		.attr("dx", function(d, i) { return i * 80 + 25;})
		.attr("dy", - 6)
		.attr("font-size", 12)
		.attr("fill", "#333")
		.attr("stroke", "none")
		.merge(months)
		.text(d => d)

	var weeks = svg.selectAll(".weeks")
		.data(["Sö", "Må", "Ti", "On", "To", "Fr", "Lö"])

	weeks = weeks
		.enter()
	.append("text")
		.attr("class", "weeks")
		.attr("dy", function(d, i) { return i * 18 + 13;})
		.attr("dx", -22)
		.attr("font-size", 11)
		.attr("fill", "#333")
		.attr("stroke", "none")
		.merge(weeks)
		.text(d => d)
}

d3.selectAll(".year").on("click", function() {
	update(Number(this.value), id)
})

d3.selectAll(".myCalendar").on("click", function() {
	console.log(d3.select(this).property("id"))
})

function pathMonth(t0) {
	var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
		d0 = t0.getDay(), w0 = d3.timeWeek.count(d3.timeYear(t0), t0),
		d1 = t1.getDay(), w1 = d3.timeWeek.count(d3.timeYear(t1), t1);
	return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
		 + "H" + w0 * cellSize + "V" + 7 * cellSize
		 + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
		 + "H" + (w1 + 1) * cellSize + "V" + 0
		 + "H" + (w0 + 1) * cellSize + "Z";
}
body {
	margin: auto;
	width: 1000px;
	font: 12px arial;
}
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>

<button class="year" value="2017">2017</button>
<button class="year" value="2018">2018</button>
<button class="year" value="2019">2019</button>

<div id="calendars"></div>

2 个答案:

答案 0 :(得分:1)

关于your own answer:根据经验,请勿在D3代码中使用循环。大多数情况下,它们是不必要的,甚至更糟的是,它们可能成为障碍,甚至使事情崩溃。

这里更简单,惯用的解决方案是将数据绑定到每个SVG。

首先,不要仅用两个字符串来绑定该数组。而是绑定data数组本身,该数组包含日期:

var svg = d3.select("#calendars").selectAll("svg")
    .data(data)
    //etc...

然后,只需在矩形中为每个用户获取这些日期...

var userDates = d3.select(this.parentNode).datum().dates;

...并使用if填充它们:

if (userDates.indexOf(d) > -1) return "red";

这是只有这些更改的代码:

var formatDay = d3.timeFormat("%d");
var formatDate = d3.timeFormat("%Y-%m-%d");

var data = [{
    id: "Some_Name",
    dates: ["2018-01-01", "2018-02-11"]
  },
  {
    id: "Another_Name",
    dates: ["2018-03-01", "2018-04-11"]
  },
]

var width = 1000,
  height = 196,
  cellSize = 18,
  transCell1 = ((width - cellSize * 53) / 2),
  transCell2 = (height - cellSize * 7 - 1);

var currentYear = new Date().getFullYear()

var svg = d3.select("#calendars").selectAll("svg")
  .data(data)
  .enter().append("svg")
  .attr("class", "myCalendar")
  .attr("id", d => d.id)
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform",
    "translate(" + transCell1 + "," + transCell2 + ")");

var names = svg.append("text")
  .attr("dx", -5)
  .attr("dy", -35)
  .attr("font-size", 14)
  .attr("text-anchor", "start")
  .text(function(d) {
    var value = d.id.split("_")
    return value[0] + " " + value[1]
  });

update(currentYear);

function update(year) {

  var getDays = function() {
    return d3.timeDays(
      new Date(year, 0, 1), new Date(year + 1, 0, 1)
    );
  }

  var fillDays = svg.selectAll(".fillDays")
    .data(getDays)

  fillDays.exit().remove()

  fillDays = fillDays
    .enter().append("rect")
    .attr("class", "fillDays")
    .attr("stroke", "#ccc")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .merge(fillDays)
    .attr("x", function(d) {
      return d3.timeWeek.count(d3.timeYear(d), d) * cellSize;
    })
    .attr("y", function(d) {
      return d.getDay() * cellSize;
    })
    .datum(d3.timeFormat("%Y-%m-%d"))
    .attr("fill", function(d) {
      var userDates = d3.select(this.parentNode).datum().dates;
      var value = new Date(d).getDay();
      var check = (value === 6 || value === 0) // Check if weekend
      if (check) return "#E0E0E0"
      if (userDates.indexOf(d) > -1) return "red" // 
      else return "none";
    });

  var days = svg.selectAll(".days")
    .data(getDays)

  days = days
    .enter().append("text")
    .attr("class", "days")
    .attr("font-size", 11)
    .attr("dy", 13)
    .attr("dx", 3)
    .style("pointer-events", "none")
    .attr("fill", "#333")
    .attr("stroke", "none")
    .merge(days)
    .attr("x", function(d) {
      return d3.timeWeek.count(d3.timeYear(d), d) * cellSize;
    })
    .attr("y", function(d) {
      return d.getDay() * cellSize;
    })
    .text(function(d) {
      return formatDay(d)
    })

  var lines = svg.selectAll("path")
    .data(function() {
      return d3.timeMonths(
        new Date(year, 0, 1), new Date(year + 1, 0, 1)
      );
    })

  lines.exit().remove()

  lines = lines
    .enter().append("path")
    .attr("fill", "none")
    .attr("stroke", "#000")
    .merge(lines)
    .attr("d", pathMonth);

  //
  // Hardcoded text
  //

  var months = svg.selectAll(".months")
    .data([
      "Jan", "Feb", "Mar", "Apr", "Maj", "Jun",
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
    ])

  months = months
    .enter()
    .append("text")
    .attr("class", "months")
    .attr("dx", function(d, i) {
      return i * 80 + 25;
    })
    .attr("dy", -6)
    .attr("font-size", 12)
    .attr("fill", "#333")
    .attr("stroke", "none")
    .merge(months)
    .text(d => d)

  var weeks = svg.selectAll(".weeks")
    .data(["Sö", "Må", "Ti", "On", "To", "Fr", "Lö"])

  weeks = weeks
    .enter()
    .append("text")
    .attr("class", "weeks")
    .attr("dy", function(d, i) {
      return i * 18 + 13;
    })
    .attr("dx", -22)
    .attr("font-size", 11)
    .attr("fill", "#333")
    .attr("stroke", "none")
    .merge(weeks)
    .text(d => d)
}

d3.selectAll(".year").on("click", function() {
  update(Number(this.value))
})

d3.selectAll(".myCalendar").on("click", function() {
  console.log(d3.select(this).property("id"))
})

function pathMonth(t0) {
  var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
    d0 = t0.getDay(),
    w0 = d3.timeWeek.count(d3.timeYear(t0), t0),
    d1 = t1.getDay(),
    w1 = d3.timeWeek.count(d3.timeYear(t1), t1);
  return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize +
    "H" + w0 * cellSize + "V" + 7 * cellSize +
    "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize +
    "H" + (w1 + 1) * cellSize + "V" + 0 +
    "H" + (w0 + 1) * cellSize + "Z";
}
body {
  margin: auto;
  width: 1000px;
  font: 12px arial;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<button class="year" value="2017">2017</button>
<button class="year" value="2018">2018</button>
<button class="year" value="2019">2019</button>
<div id="calendars"></div>

答案 1 :(得分:0)

因此,我想出了自己的基于jonnys注释的解决方案,我将数据包含在update参数中并进行forEach循环,基于id选择svg,并使用与以前大致相同的逻辑。 / p>

allData.forEach(function(data, i) {

    d3.selectAll("#" + user[i]).selectAll(".fillDays").attr("fill", function(d) {
        var value = new Date(d).getDay();
        var check = (value === 6 || value === 0) // Check if weekend
        if (check) return "#E0E0E0"
        if (data.dates.includes(d)) return "red"
        else return "none"; 
    })
})

这是我目前能想到的最干净的解决方案,如果您有更好的解决方案,请随时回答。

var formatDay = d3.timeFormat("%d");
var formatDate = d3.timeFormat("%Y-%m-%d");

var sqlData = [
	{id: "Some_Name", dates: ["2018-01-01", "2018-02-12"]},
	{id: "Another_Name", dates: ["2018-03-01", "2018-04-11"]},
]

var width = 1000,
	height = 196,
	cellSize = 18,
	transCell1 = ((width - cellSize * 53) / 2),
	transCell2 = (height - cellSize * 7 - 1);

var currentYear = new Date().getFullYear()

var id = [...new Set(sqlData.map(function(d) {
	return d.id
}))];

var svg = d3.select("#calendars").selectAll("svg")
	.data(id)
.enter().append("svg")
	.attr("class", "myCalendar")
	.attr("id", d => d)
	.attr("width", width)
	.attr("height", height)
.append("g")
	.attr("transform", 
		"translate(" + transCell1 + "," + transCell2 +")");

var names = svg.append("text")
	.attr("dx", - 5)
	.attr("dy", - 35)
	.attr("font-size", 14)
	.attr("text-anchor", "start")
	.text(function(d) {
		var value = d.split("_")
		return value[0] + " " + value[1]
	});

d3.selectAll(".year").on("click", function() {
	update(Number(this.value), id, sqlData)
})

update(currentYear, id, sqlData);

function update(year, user, allData) {

	var getDays = function() { 
			return d3.timeDays(
				new Date(year, 0, 1), new Date(year + 1, 0, 1)
			);
		}

	var fillDays = svg.selectAll(".fillDays")
		.data(getDays)

	fillDays.exit().remove()

	fillDays = fillDays
	.enter().append("rect")
		.attr("class", "fillDays")
		.attr("stroke", "#ccc")
		.attr("width", cellSize)
		.attr("height", cellSize)
		.merge(fillDays)
		.attr("x", function(d) { 
			return d3.timeWeek.count(d3.timeYear(d), d) * cellSize;
		})
		.attr("y", function(d) { return d.getDay() * cellSize; })
		.datum(d3.timeFormat("%Y-%m-%d"))

	var days = svg.selectAll(".days")
		.data(getDays)

	days = days
	.enter().append("text")
		.attr("class", "days")
		.attr("font-size", 11)
		.attr("dy", 13)
		.attr("dx", 3)
		.style("pointer-events", "none")
		.attr("fill", "#333")
		.attr("stroke", "none")
		.merge(days)
		.attr("x", function(d) {
			return d3.timeWeek.count(d3.timeYear(d), d) * cellSize;
		})
		.attr("y", function(d) { return d.getDay() * cellSize; })
		.text(function(d) {
			return formatDay(d)
		})
	
	var lines = svg.selectAll("path")
		.data(function() { 
			return d3.timeMonths(
				new Date(year, 0, 1), new Date(year + 1, 0, 1)
			); 
		})

	lines.exit().remove()

	lines = lines
	.enter().append("path")
		.attr("fill", "none")
		.attr("stroke", "#000")
		.merge(lines)
		.attr("d", pathMonth);

	//
	// Hardcoded text
	//

	var months = svg.selectAll(".months")
		.data([
			"Jan", "Feb", "Mar", "Apr", "Maj", "Jun", 
			"Jul", "Aug", "Sep", "Okt", "Nov", "Dec"])

	months = months
		.enter()
	.append("text")
		.attr("class", "months")
		.attr("dx", function(d, i) { return i * 80 + 25;})
		.attr("dy", - 6)
		.attr("font-size", 12)
		.attr("fill", "#333")
		.attr("stroke", "none")
		.merge(months)
		.text(d => d)

	var weeks = svg.selectAll(".weeks")
		.data(["Sö", "Må", "Ti", "On", "To", "Fr", "Lö"])

	weeks = weeks
		.enter()
	.append("text")
		.attr("class", "weeks")
		.attr("dy", function(d, i) { return i * 18 + 13;})
		.attr("dx", -22)
		.attr("font-size", 11)
		.attr("fill", "#333")
		.attr("stroke", "none")
		.merge(weeks)
		.text(d => d)

	allData.forEach(function(data, i) {

		d3.selectAll("#" + user[i]).selectAll(".fillDays").attr("fill", function(d) {
			var value = new Date(d).getDay();
			var check = (value === 6 || value === 0) // Check if weekend
			if (check) return "#E0E0E0"
			if (data.dates.includes(d)) return "red"
			else return "none"; 
		})
	})
}

function pathMonth(t0) {
	var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
		d0 = t0.getDay(), w0 = d3.timeWeek.count(d3.timeYear(t0), t0),
		d1 = t1.getDay(), w1 = d3.timeWeek.count(d3.timeYear(t1), t1);
	return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
		 + "H" + w0 * cellSize + "V" + 7 * cellSize
		 + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
		 + "H" + (w1 + 1) * cellSize + "V" + 0
		 + "H" + (w0 + 1) * cellSize + "Z";
}
body {
	margin: auto;
	width: 1000px;
	font: 12px arial;
}	
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>

<button class="year" value="2017">2017</button>
<button class="year" value="2018">2018</button>
<button class="year" value="2019">2019</button>

<div id="calendars"></div>

相关问题