Skip to content

Instantly share code, notes, and snippets.

@jdunkerley
Last active November 14, 2018 16:11
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/d4d6b3e2a968ec94224dd09fca391f30 to your computer and use it in GitHub Desktop.
Save jdunkerley/d4d6b3e2a968ec94224dd09fca391f30 to your computer and use it in GitHub Desktop.
AlterD3 Simple Bar Chart
<!-- ref: https://d3js.org/d3.v5.min.js //-->
<!-- Input Expected: Name, Value //-->
<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 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())
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())
svg.append("g").call(xAxis)
svg.append("g").call(yAxis)
</script>
</div>

Taking the example from D3 Bar Chart

By default the data should have a 'Name' and 'Value' columns. The 'Value' should be numeric.

        const data = alteryxData()
        const getX = d => d.Name
        const getY = d => d.Value

This section controls how the data is read from the Alteryx input. You can change the column names by adjusting the arrow functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment