我对使用d3.js的图表有疑问。我想从图表中隐藏一个特定的时间间隔,该时间间隔是静态的(例如:从16:00到18:00)。我是否需要在不使用此间隔的情况下创建自定义比例,否则d3.js可以提供简单的解决方案?
var width = 960,
height = 500;
var fmtMonth = d3.time.format("%b");
var date1 = new Date(2018, 9, 26);
var date2 = new Date(2018, 9, 27);
var date3 = new Date(2018, 9, 28);
var date4 = new Date(2018, 9, 29);
var dates = [date1, date2, date3, date4];
var vis = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var linear = vis.append("g").attr("transform", "translate(20, 10)"),
polyLinear = vis.append("g").attr("transform", "translate(20, 100)");
// poly linear scale
var tickWidth = (940) / (dates.length - 1);
var range = dates.map(function (d, i) { return (i * tickWidth); });
var polylinearTimeScale = d3.time.scale()
.domain(dates)
.range(range);
var polylinearAxis = d3.svg.axis().scale(polylinearTimeScale);
var ticks = polylinearTimeScale.ticks();
// Filter by removing 6 hours
var displayTicks = ticks.filter(date => date.getHours() !== 6);
polylinearAxis.tickValues(displayTicks);
polylinearAxis.tickFormat(d3.time.format("%H:%M"))
polyLinear.append("g").attr("class", "x axis").call(polylinearAxis);
如您所见,在00:00和12:00之间不应有空格。我希望从图表中清除此空间,因此00:00和12:00之间的宽度就像12:00和18:00之间的宽度
答案 0 :(得分:1)
尝试将数据结构整理为更可用的格式。然后使用序数或带刻度。
const width = 600;
const height = 200;
const data = [{
val: 10,
date: "Mon 12:00"
},
{
val: 1,
date: "Mon 18:00"
},
{
val: 7,
date: "Tue 12:00"
},
{
val: 3,
date: "Tue 18:00"
},
{
val: 9,
date: "Wed 12:00"
},
{
val: 5,
date: "Wed 18:00"
}
]
const xDomain = data.map((x) => x.date)
const vis = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
const ordinalAxis = vis.append("g")
const x = d3.scale.ordinal()
.domain(xDomain)
.rangeBands([0, width]);
const xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
vis.append("g")
.attr('transform', `translate(0, ${height-30})`)
.attr("class", "x axis")
.call(xAxis);
const barGroup = vis.append('g')
barGroup.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', d => x(d.date))
.attr('y', d => height - d.val * 15 - 30)
.attr('width', width / data.length)
.attr('height', d => d.val * 15)
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #1c647e;
shape-rendering: crispEdges;
}
rect {
fill: #55accf
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
答案 1 :(得分:0)
在这种情况下,您打算做的是操纵DOM。但是对于D3(数据驱动的文档),您需要考虑数据。对于要隐藏的期间,可以生成或过滤数据以将其删除,然后图形将自动反映更改。
编辑: 发表评论后,您可以使用@ckersch中的答案来完成此操作:only display certain hours with d3.js