Skip to content

Instantly share code, notes, and snippets.

@BenoitZugmeyer
Created May 14, 2018 22:51
Show Gist options
  • Save BenoitZugmeyer/2016a12d24d2f7f971d009154ed518fa to your computer and use it in GitHub Desktop.
Save BenoitZugmeyer/2016a12d24d2f7f971d009154ed518fa to your computer and use it in GitHub Desktop.
const colors = ["red", "blue", "yellow", "white", "black"]
function createChart(width, height) {
const svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", `0 0 ${width} ${height}`)
.attr("style", "background-color: grey; margin: 10px")
const cellsPerDomain = 24
const maxCellSize = 12
const minCellCount = cellsPerDomain * 2
const minRowCount = Math.ceil(Math.sqrt(minCellCount / (width / height)))
const minCellSizeWithSpacing = height / minRowCount
const minCellSize = minCellSizeWithSpacing * 0.8
const cellSize = Math.floor(Math.min(maxCellSize, minCellSize))
const cellSpacing = Math.floor(cellSize * 0.2)
const cellSizeWithSpacing = cellSize + cellSpacing
const rowCount = Math.floor((height - cellSpacing) / (cellSize + cellSpacing))
const columnCount = Math.floor((width - cellSpacing) / cellSizeWithSpacing)
const cellCount = rowCount * columnCount
const cellLeft = Math.floor((width - (columnCount * cellSizeWithSpacing - cellSpacing)) / 2)
const cellTop = Math.floor((height - (rowCount * cellSizeWithSpacing - cellSpacing)) / 2)
console.log(width, cellSpacing, cellSize, columnCount)
console.log(cellLeft)
const cellRow = c => rowCount - 1 - c % rowCount
const cellColumn = c => columnCount - 1 - Math.floor(c / rowCount)
const domainFirstCell = d => d * cellsPerDomain
const domainLastCell = d => domainFirstCell(d + 1) - 1
const cellToDomain = c => Math.floor(c / cellsPerDomain)
//console.log(cellToDomain(cellCount), cellSize)
svg.selectAll(".cell")
.data(d3.range(0, cellCount))
.enter()
.append("rect")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("fill", c => colors[cellToDomain(c) % colors.length])
.attr("x", c => {
const a = cellColumn(c) * cellSizeWithSpacing + cellLeft
// console.log(a)
return a
})
.attr("y", c => cellRow(c) * cellSizeWithSpacing + cellTop)
}
createChart(100, 100)
/*createChart(200, 100)
createChart(400, 150)
createChart(150, 400)*/
//createChart(100, 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment