JSFiddle - React, Tailwind, and code Playground
by andrewarnier
CSS
.title {
font-size: 40pt;
}
.axis {
fill: none;
stroke: black;
stroke-width: 1;
shape-rendering: crispEdges;
}
.axis text {
fill: black;
stroke: none;
}
JavaScript
// Create Global Variable
var dataset;
dataset = [
{CustomerCount: Math.floor(Math.random()*250),State: "FL"},
{CustomerCount: 25,State: "GA"},
{CustomerCount: 10,State: "NY"},
{CustomerCount: 200,State: "TX"},
{CustomerCount: 1400,State: "ALL"}
]
// Call function
Graph(dataset);
// Create function
function Graph(input) {
// Declare Variables
var margin = {top: 60, right: 60, bottom: 60, left:120},
w = 600 - margin.left - margin.right,
h = 400 - margin.top - margin.bottom;
// update the margin based on the title size
var titleSize = measure("Title of Diagram", "title");
margin.top = titleSize.height + 20;
//Create X Scale for bar graph
var xScale = d3.scale.ordinal()
.domain(input.map(function (d){ return d.State;}))
.rangeRoundBands([0, w], 0.05);
//Create Y Scale for bar graph
var yScale = d3.scale.linear()
.domain([0,d3.max(input, function(d) { return d.CustomerCount; })])
.range([h, 0]);
//Create X Axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
//Create Y Axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left');
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom)
.append('g')
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Create X axis
svg.append("g")
.attr("class", "axis x")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
//Create Title
svg.append("text")
.attr("x", w / 2 )
.attr("y", -titleSize.height/2 + 10)
.attr("class", "title")
.style("text-anchor", "middle")
.text("Title of Diagram");
//Create X axis label
svg.append("text")
.attr("x", w / 2 )
.attr("y", h + margin.bottom)
...