Skip to content

Instantly share code, notes, and snippets.

@jdunkerley
Created November 13, 2018 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdunkerley/ab6b069a6580ab3a046a5400111ad831 to your computer and use it in GitHub Desktop.
Save jdunkerley/ab6b069a6580ab3a046a5400111ad831 to your computer and use it in GitHub Desktop.
AlterD3 Coloured Bar Chart
<!-- ref: https://d3js.org/d3.v5.min.js //-->
<!-- Input Expected: Name, Value, Set //-->
<style>
</style>
<div id="ChartHtml">
<div id="chart1" style="background-color: white;">
<svg id="chartSVG" style="width:800px; height:600px;background-color: white;"></svg>
</div>
<script>
const svg = d3.select("#chartSVG")
const width = +svg.style("width").replace("px","")
const height = +svg.style("height").replace("px","")
const margin = { left: 30, right: 10, top: 5, bottom: 30}
// Access Data Here
const data = alteryxData()
const getX = d => d.Name
const getY = d => d.Value
const getSet = d => d.Set
const x = d3.scaleBand().domain(data.map(getX)).range([margin.left, width - margin.right]).padding(0.1)
const xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x)
.tickSizeOuter(0))
const y = d3.scaleLinear().domain([0, d3.max(data, getY)]).nice().range([height - margin.bottom, margin.top])
const yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
const sets = data.map(getSet).filter((v, i, a) => a.indexOf(v) === i)
const colourScale = d3.scaleOrdinal(d3.schemeCategory10)
const color = d => colourScale(d => sets.indexOf(getSet(d)))
svg.append("g")
.attr("fill", "steelblue")
.selectAll("rect").data(data).enter().append("rect")
.attr("x", d => x(getX(d)))
.attr("y", d => y(getY(d)))
.attr("height", d => y(0) - y(getY(d)))
.attr("width", x.bandwidth())
.attr("fill", color)
svg.append("g").call(xAxis)
svg.append("g").call(yAxis)
</script>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment