Skip to content

Instantly share code, notes, and snippets.

@BenoitZugmeyer
Created May 14, 2018 22:10
Show Gist options
  • Save BenoitZugmeyer/c99a4f2e75d1874c2f05342a9caec67e to your computer and use it in GitHub Desktop.
Save BenoitZugmeyer/c99a4f2e75d1874c2f05342a9caec67e 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("style", "background-color: grey; margin: 10px")
const minCellSize = 16
const cellSpacing = 6
const rowCount = Math.floor((height - cellSpacing) / (minCellSize + cellSpacing))
const cellSize = Math.floor((height - cellSpacing) / rowCount - cellSpacing)
const cellSizeWithSpacing = cellSize + cellSpacing
const columnCount = Math.floor((width - cellSpacing) / cellSizeWithSpacing)
const cellCount = rowCount * columnCount
console.log(cellSize, columnCount)
const cellsPerDomain = 24
/* const domainCount = Math.floor(cellCount / cellsPerDomain)
const cellCount = domainCount * cellsPerDomain
const columnCount = Math.ceil(cellCount / rowCount)*/
const cellLeft = Math.round((width - (columnCount * cellSizeWithSpacing + cellSpacing)) / 2) + cellSpacing
const cellTop = Math.round((height - (rowCount * cellSizeWithSpacing + cellSpacing)) / 2) + cellSpacing
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))
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 => cellColumn(c) * cellSizeWithSpacing + cellLeft)
.attr("y", c => cellRow(c) * cellSizeWithSpacing + cellTop)
}
/*
createChart(100, 100)
createChart(200, 100)
*/
createChart(100, 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment