Skip to content

Instantly share code, notes, and snippets.

@ckinmind
Last active January 3, 2018 02:48
Show Gist options
  • Save ckinmind/3d5d17b992e3f4c7f3ae1b134bf1902f to your computer and use it in GitHub Desktop.
Save ckinmind/3d5d17b992e3f4c7f3ae1b134bf1902f to your computer and use it in GitHub Desktop.
histogram——力图实现散点不重叠(固定圆半径)

说明

知识点

  • d3.forceSimulation 创建一个力模拟
  • d3.forceX 创建x-定位力
  • d3.forceY 创建y-定位力
  • d3.forceCollide 创建一个圆碰撞力
  • d3.forceManyBody 创建多体力
const typeArr = [
'feature', // 功能需求
'bug', // bug fix
'meeting', // 开会
'other' // 其他
]
const timeArr = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]
const getType = () => {
const num = Math.round(Math.random() * 100)
return num < 70 ? 'feature' : (num < 75 ? 'bug' : (num < 90 ? 'other' : 'meeting'))
}
const generate = (date, key, count) => {
return d3.range(0, count).map((item, index) => {
const num = (Math.random() * 15 + 8).toFixed(0)
return {
id: key + index,
date: `${date}-${num}`,
timeLength: timeArr[Math.round(Math.random() * 7)],
type: getType(),
}
})
}
const arr1 = generate('2017-12-18', 'a', 65)
const arr2 = generate('2017-12-19', 'b', 100)
const arr3 = generate('2017-12-20', 'c', 25)
const arr4 = generate('2017-12-21', 'd', 55)
const arr5 = generate('2017-12-22', 'e', 45)
const arr6 = generate('2017-12-23', 'f', 43)
const arr7 = generate('2017-12-24', 'g', 22)
const data = [
...arr1,
...arr2,
...arr3,
...arr4,
...arr5,
...arr6,
...arr7,
]
<!DOCTYPE html>
<head>
<meta charset='utf-8'>
<style>
body {
font-family:'avenir next', Arial, sans-serif;
font-size: 12px;
color: #696969;
}
#vis{
margin: 0 auto;
width: 900px;
height: 500px;
}
.ticks {
font-size: 10px;
}
.track-overlay {
pointer-events: stroke;
stroke-width: 50px;
stroke: transparent;
/*cursor: crosshair;*/
}
.drag-layer {
/*cursor: crosshair*/
}
.handle {
/*fill: #fff;*/
/*stroke: #000;*/
/*stroke-opacity: 0.5;*/
/*stroke-width: 1.25px;*/
}
</style>
</head>
<body>
<div id='vis'></div>
<script src='https://d3js.org/d3.v4.min.js'></script>
<script src='./data.js'></script>
<script>
console.log(data)
const margin = {top:50, right:50, bottom:50, left:50},
width = 900 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom
const histHeight = 100
const parseDate = d3.timeParse('%Y-%m-%d-%H')
const formatDateIntoDay = d3.timeFormat('%d')
const startDate = new Date('2017-12-18 00:00:00')
const endDate = new Date('2017-12-25 00::00:00')
const dateArray = d3.timeDays(startDate, endDate)
data.forEach(d => {
d.date = parseDate(d.date)
d.day = formatDateIntoDay(d.date)
})
// 颜色比例尺
const colors = d3.scaleOrdinal()
.domain(dateArray)
.range(['#409ffb', '#85d1ea', '#65cccb', '#77debd', '#6ccb74', '#abdf81', '#fbd340']);
const colorObj = {
feature: '#409ffb',
bug: '#fbd340',
meeting: '#f1627b',
other: '#abdf81'
}
// x轴比例尺
const x = d3.scaleTime()
.domain([startDate, endDate])
.range([0, width])
.clamp(true) // time.clamp - 启用闭合, 意思是如果入参超出定义域,则返回值会直接显示为边界值,查看https://github.com/d3/d3-scale#continuous_clamp
// 直方图生成器
const histogram = d3.histogram() // histogram 将离散样本分成连续的无重叠的间隔
.value(d => d.date) // histogram.value - 为每个样本指定一个值访问器
.domain(x.domain()) // histogram.domain - 指定可观测值的间隔
// .thresholds(x.ticks(d3.timeDay)) // histogram.thresholds - 指定值划分成不同箱的方法
.thresholds(dateArray) // histogram.thresholds - 指定值划分成不同箱的方法
const bins = histogram(data)
// y轴比例尺
const y = d3.scaleLinear()
.domain([0, d3.max(bins, d => d.length)])
.range([0, histHeight])
const y2 = d3.scaleLinear()
.domain([0, d3.max(data, d => d.timeLength)])
.range([0, 200])
const svg = d3.select('#vis')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
// 直方图容器g
const hist = svg.append('g')
.attr('class', 'histogram')
.attr('transform', `translate(${margin.left}, ${margin.top})`)
// 散点图容器g
const plot = svg.append('g')
.attr('class', 'plot')
.attr('transform', `translate(${margin.left}, ${margin.top + histHeight + 50})`)
plot.append('g')
.attr('class', 'axis axis--y')
.call(d3.axisLeft(y2))
drawHistogram() // 绘制直方部分
function drawHistogram() {
const bar = hist.selectAll('.bar')
.data(bins)
.enter()
.append('g')
.attr('transform', d => `translate(${x(d.x0)}, ${histHeight - y(d.length)})`)
bar.append('rect')
.attr('class', 'bar')
.attr('width', d => x(d.x1) - x(d.x0) - 1) // 1是柱子间的间隔
.attr('height', d => y(d.length))
.attr('fill', '#eaeaea')
.attr('stroke', '#000')
bar.append('text')
.attr('dy', '.75em')
.attr('y', '6')
.attr('x', d => (x(d.x1) - x(d.x0))/2)
.attr('text-anchor', 'middle')
.text(d => d.length)
.attr('fill', '#000')
}
const simulation = d3.forceSimulation(data)
.force('x', d3.forceX(d => x(d.date)).strength(1))
.force('y', d3.forceY(d => y2(d.timeLength)))
.force('collide', d3.forceCollide().radius(d => 5))
.force('manyBody', d3.forceManyBody().strength(2))
.stop()
for (var i = 0; i < 100; ++i) simulation.tick();
const circle = plot.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('fill', d => colorObj[d.type])
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', 5 )
.style('opacity', 0.6)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment