Related
I am trying to create two heatmaps showing different data updated by a common date drop down. I am using heatmap with data update and creating two separate svgs to update when a new date field is selected in the dropdown. I was able to follow some of the SO answers to create two plots in the same page, but I am totally clueless as to have just one drop down of the locations update both charts simultaneously. Any pointers on how to achieve this would be greatly appreciated. I have included the code I have been working with and the json data. I have the data in two different files for now. Would be even better if it can be just from one file to make it easier to read the location dropdown value.
var dataset;
var dataset2;
var days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
times = d3.range(24);
var margin = {top:40, right:50, bottom:70, left:50};
// calculate width and height based on window size
var w = Math.max(Math.min(window.innerWidth, 1000), 500) - margin.left - margin.right - 20,
gridSize = Math.floor(w / times.length),
h = gridSize * (days.length+2);
//reset the overall font size
var newFontSize = w * 62.5 / 900;
d3.select("html").style("font-size", newFontSize + "%");
// svg container
var svg = d3.select("#heatmap")
.append("svg")
.attr("width", w + margin.top + margin.bottom)
.attr("height", h + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// svg container
var svg2 = d3.select("#heatmap2")
.append("svg")
.attr("width", w + margin.top + margin.bottom)
.attr("height", h + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// linear colour scale
var colours = d3.scaleLinear()
.domain(d3.range(1, 11, 1))
.range(["#87cefa", "#86c6ef", "#85bde4", "#83b7d9", "#82afce", "#80a6c2", "#7e9fb8", "#7995aa", "#758b9e", "#708090"]);
var dayLabels = svg.selectAll(".dayLabel")
.data(days)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", 0)
.attr("y", function(d, i) { return i * gridSize; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
var dayLabels = svg2.selectAll(".dayLabel")
.data(days)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", 0)
.attr("y", function(d, i) { return i * gridSize; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", function(d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)");
var timeLabels = svg2.selectAll(".timeLabel")
.data(times)
.enter()
.append("text")
.text(function(d) { return d; })
.attr("x", function(d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)");
// load data heatmap 1
d3.json("test.json", function(error, data) {
data.forEach(function(d) {
d.day = +d.day;
d.hour = +d.hour;
d.value = +d.value;
});
dataset = data;
// group data by location
var nest = d3.nest()
.key(function(d) { return d.location; })
.entries(dataset);
// array of locations in the data
var locations = nest.map(function(d) { return d.key; });
var currentLocationIndex = 0;
// create location dropdown menu
var locationMenu = d3.select("#locationDropdown1");
locationMenu
.append("select")
.attr("id", "locationMenu")
.selectAll("option")
.data(locations)
.enter()
.append("option")
.attr("value", function(d, i) { return i; })
.text(function(d) { return d; });
// function to create the initial heatmap
var drawHeatmap = function(location) {
// filter the data to return object of location of interest
var selectLocation = nest.find(function(d) {
return d.key == location;
});
var heatmap = svg.selectAll(".hour")
.data(selectLocation.values)
.enter()
.append("rect")
.attr("x", function(d) { return (d.hour-1) * gridSize; })
.attr("y", function(d) { return (d.day-1) * gridSize; })
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("stroke", "white")
.style("stroke-opacity", 0.6)
.style("fill", function(d) { return colours(d.value); })
}
drawHeatmap(locations[currentLocationIndex]);
var updateHeatmap = function(location) {
// filter data to return object of location of interest
var selectLocation = nest.find(function(d) {
return d.key == location;
});
// update the data and redraw heatmap
var heatmap = svg.selectAll(".hour")
.data(selectLocation.values)
.transition()
.duration(500)
.style("fill", function(d) { return colours(d.value); })
}
// run update function when dropdown selection changes
locationMenu.on("change", function() {
// find which location was selected from the dropdown
var selectedLocation = d3.select(this)
.select("select")
.property("value");
currentLocationIndex = +selectedLocation;
// run update function with selected location
updateHeatmap(locations[currentLocationIndex]);
});
})
// load data heatmap 2
d3.json("test2.json", function(error, data2) {
data2.forEach(function(d2) {
d2.day = +d2.day;
d2.hour = +d2.hour;
d2.value = +d2.value;
});
dataset2 = data2;
// group data by location
var nest2 = d3.nest()
.key(function(d2) { return d2.location; })
.entries(dataset2);
// array of locations in the data
var locations2 = nest2.map(function(d2) { return d2.key; });
var currentLocationIndex2 = 0;
// create location dropdown menu
var locationMenu2 = d3.select("#locationDropdown2");
locationMenu2
.append("select")
.attr("id", "locationMenu")
.selectAll("option")
.data(locations2)
.enter()
.append("option")
.attr("value", function(d2, i2) { return i2; })
.text(function(d2) { return d2; });
// function to create the initial heatmap
var drawHeatmap2 = function(location2) {
// filter the data to return object of location of interest
var selectLocation2 = nest2.find(function(d2) {
return d2.key == location2;
});
var heatmap2 = svg2.selectAll(".hour")
.data(selectLocation2.values)
.enter()
.append("rect")
.attr("x", function(d2) { return (d2.hour-1) * gridSize; })
.attr("y", function(d2) { return (d2.day-1) * gridSize; })
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("stroke", "white")
.style("stroke-opacity", 0.6)
.style("fill", function(d2) { return colours(d2.value); })
}
drawHeatmap2(locations2[currentLocationIndex2]);
var updateHeatmap2 = function(location2) {
console.log("currentLocationIndex: " + currentLocationIndex2)
// filter data to return object of location of interest
var selectLocation2 = nest2.find(function(d2) {
return d2.key == location2;
});
// update the data and redraw heatmap
var heatmap2 = svg2.selectAll(".hour")
.data(selectLocation2.values)
.transition()
.duration(500)
.style("fill", function(d2) { return colours(d2.value); })
}
// run update function when dropdown selection changes
locationMenu2.on("change", function() {
// find which location was selected from the dropdown
var selectedLocation2 = d3.select(this)
.select("select")
.property("value");
currentLocationIndex2 = +selectedLocation2;
// run update function with selected location
updateHeatmap2(locations2[currentLocationIndex2]);
});
})
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
html {
font-size: 62.5%;
}
body {
margin-top: 30px;
font-size: 1.4rem;
font-family: 'Source Sans Pro', sans-serif;
font-weight: 400;
fill: #696969;
text-align: center;
}
.timeLabel, .dayLabel {
font-size: 1.6rem;
fill: #AAAAAA;
font-weight: 300;
}
#nav-container {
display: flex;
justify-content: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="nav-container">
<div id="locationDropdown1"></div>
</div>
<div id="heatmap"></div>
<div id="nav-container">
<div id="locationDropdown2"></div>
</div>
<div id="heatmap2"></div>
JSON sample is the same as the link above .. just with some values modified to show differentiation. (Not sure how to include a big json file on here). Thanks again.
I am new to java script and I am trying to draw a radar chart. Everything works well except title. Can u please tell me what is wrong? I attached the code below. First I create text var and call it to show.
<style>
body {
overflow: hidden;
margin: 0;
font-size: 14px;
font-family: "Helvetica Neue", Helvetica;
}
#chart {
position: absolute;
top: 60px;
left: 20px;
}
</style>
<script type="text/javascript" src="<c:url value='/js/radar.js'/>"></script>
<div id="body">
<div id="chart"></div>
</div>
<script>
var w = 200;
var h = 200;
var colorscale = d3.scale.category10();
//Legend, titles
var LegendOptions = ['Try Count','Succcess Count', 'Success Rate'];
////////////////////////////////////////////
/////////// Initiate legend ////////////////
////////////////////////////////////////////
var svg = d3.select('#body')
.selectAll('svg')
.append('svg')
.attr("width", w+300)
.attr("height", h)
//Create the title for the legend
var text = svg.append("text")
.attr("class", "title")
.attr('transform', 'translate(90,0)')
.attr("x", w - 70)
.attr("y", 10)
.attr("font-size", "12px")
.attr("fill", "#404040")
.text("What % of owners use a specific service in a week");
//Initiate Legend
var legend = svg.append("g")
.attr("class", "legend")
.attr("height", 100)
.attr("width", 200)
.attr('transform', 'translate(90,20)')
;
//Create colour squares
legend.selectAll('rect')
.data(LegendOptions)
.enter()
.append("rect")
.attr("x", w - 65)
.attr("y", function(d, i){ return i * 20;})
.attr("width", 10)
.attr("height", 10)
.style("fill", function(d, i){ return colorscale(i);})
;
//Create text next to squares
legend.selectAll('text')
.data(LegendOptions)
.enter()
.append("text")
.attr("x", w - 52)
.attr("y", function(d, i){ return i * 20 + 9;})
.attr("font-size", "11px")
.attr("fill", "#737373")
.text(function(d) { return d; })
;
//Options for the Radar chart, other than default
var mycfg = {
w: w,
h: h,
maxValue: 0.6,
levels: 6,
ExtraWidthX: 300
}
Try changing:
var svg = d3.select('#body')
.selectAll('svg')
.append('svg')....
To:
var svg = d3.select('#body')
.append('svg')....
As you are only appending one svg, you do not need the selectAll() portion. The following takes your code and makes that one change:
var w = 200;
var h = 200;
var svg = d3.select('#body')
.append('svg')
.attr("width", w+300)
.attr("height", h)
var text = svg.append('g').append("text")
.attr("class", "title")
.attr('transform', 'translate(90,0)')
.attr("x", w - 70)
.attr("y", 10)
.attr("font-size", "12px")
.attr("fill", "#404040")
.text("What % of owners use a specific service in a week");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="body"></div>
Hi this is my first post. I've searched for a good tutorial to help finish this D3 line chart - but haven't found what I'm looking for. All I need to do is get the orange circle to follow the same path as the dotted line. At the moment it has a straight path. Thanks for any help on this.
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!-->
<html lang="en"><!--<![endif]-->
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Drawdown line chart</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
body {font: 15px sans-serif;}
.container{max-width:990px}
h2{float:left; width:100%; text-align:center; font-size:30px; color:#666666; margin:20px 0 30px}
.highlight{color:#f26522}
#chart{width:90%; margin:0 10%}
.domain {fill: none; stroke: gray; stroke-width: 1;}
</style>
</head>
<body>
<div class="container">
<h2>Click the <span class="highlight">orange dot</span> to start:</h2>
<div class="row">
<div id="chart" class="col-sm-12">
</div>
</div>
</div>
<script type="text/javascript">
// Chart data
var dataArray = [
{"x":0, "y":100000},
{"x":1, "y":90000},
{"x":2, "y":83000},
{"x":3, "y":73000},
{"x":4, "y":79000},
{"x":5, "y":72000},
{"x":6, "y":75000},
{"x":7, "y":88000},
{"x":8, "y":63000},
{"x":9, "y":71000},
{"x":10, "y":69000},
{"x":11, "y":63000},
{"x":12, "y":67000},
{"x":13, "y":63000},
{"x":14, "y":59000},
{"x":15, "y":46000},
{"x":16, "y":40000},
{"x":17, "y":32000},
{"x":18, "y":29000},
{"x":19, "y":20000},
{"x":20, "y":18000},
{"x":21, "y":17000},
{"x":22, "y":9000},
{"x":23, "y":0},
{"x":24, "y":0},
{"x":25, "y":0},
{"x":26, "y":0},
{"x":27, "y":0},
{"x":28, "y":0},
{"x":29, "y":0},
{"x":30, "y":0}
];
// Variables
var currentAge = 65
var longevity = 92
var yearsToLive = longevity - currentAge
var years = dataArray.length
var totalDrawdown = dataArray[0].y
var chartWidth = 800
var chartHeight = 400
var chartMargin = 20
var axisHeight = 20
var widthScale = d3.scale.linear()
.domain([currentAge, currentAge + years])
.range([0, chartWidth - chartMargin]);
var axis = d3.svg.axis()
.ticks(5)
.tickSize(20)
.scale(widthScale);
// Chart scaling
x_scale = d3.scale.linear().domain([0,years]).range([0, chartWidth]);
y_scale = d3.scale.linear().domain([0,totalDrawdown]).range([chartHeight - chartMargin,0]);
var lineFunction = d3.svg.line()
.x(function(d) { return x_scale(d.x) })
.y(function(d) { return y_scale(d.y) });
function getSmoothInterpolation() {
var interpolate = d3.scale.linear()
.domain([0,1])
.range([1, dataArray.length + 1]);
return function(t) {
var flooredX = Math.floor(interpolate(t));
var interpolatedLine = dataArray.slice(0, flooredX);
if(flooredX > 0 && flooredX < dataArray.length) {
var weight = interpolate(t) - flooredX;
var weightedLineAverage = dataArray[flooredX].y * weight + dataArray[flooredX-1].y * (1-weight);
interpolatedLine.push({"x":interpolate(t)-1, "y":weightedLineAverage});
}
return lineFunction(interpolatedLine);
}
}
// Canvas
var canvas = d3.select ("#chart")
.append("svg")
.attr("width", chartWidth)
.attr("height", chartHeight + axisHeight)
.attr("id", "lineChart");
// Longevity marker
var rectangle = canvas.append("rect")
.attr("width", (chartWidth/years) * ((currentAge + years) - longevity))
.attr("height", chartHeight - chartMargin)
.attr("x", (chartWidth/years) * (longevity - currentAge) )
.attr("fill","#f2f2f2");
// Destination range
var outer = canvas.append("rect")
.attr("width", 200)
.attr("height", 10)
.attr("x", 525 )
.attr("y", 380 )
.attr("fill","#f2f2f2");
var inner = canvas.append("rect")
.attr("width", 75)
.attr("height", 10)
.attr("x", 588 )
.attr("y", 380 )
.attr("fill","#d1d1d1");
var likely = canvas.append("rect")
.attr("width", 10)
.attr("height", 10)
.attr("x", 620 )
.attr("y", 380 )
.attr("fill","#666666");
// Chart path
canvas.append("path")
.attr("stroke-width", 2)
.attr("stroke", "gray")
.attr("fill", "none")
.attr("id", "journey")
.style("stroke-dasharray", ("3, 3"))
.attr("transform", "translate(" + chartMargin + ", 0)")
// Moving circle
var marker = canvas.append("circle")
.attr("id", "marker")
.attr("cx", 5 + chartMargin)
.attr("cy", 10)
.attr("r", 10)
.attr('fill', '#f26522');
// Add x axis
canvas.append("g")
.attr("transform", "translate("+ chartMargin + "," + (chartHeight - chartMargin) + ")")
.attr("fill","#aaaaaa")
.call(axis);
// Add start button
d3.select('#lineChart')
.append('circle')
.attr("cx", 5 + chartMargin)
.attr("cy", 10)
.attr("r", 10)
.attr('fill', '#f26522')
.on('click', function() {
d3.select('#lineChart > #journey')
.transition()
.duration(6000)
.attrTween('d', getSmoothInterpolation );
d3.select('#lineChart > #marker')
.transition()
.duration(6000)
.attrTween("cx", function (d, i, a) { return d3.interpolate(a, 620) })
.attrTween("cy", function (d, i, a) { return d3.interpolate(a, 400) });
});
</script>
</body>
</html>
Here is my try:
Instead of translating the circle via transition like this in the click function:
d3.select('#lineChart > #marker')
.transition()
.duration(6000)
.attrTween("cx", function (d, i, a) { return d3.interpolate(a, 620) })
.attrTween("cy", function (d, i, a) { return d3.interpolate(a, 400) });
Move the circle animation also with in the path animation like below:
function getSmoothInterpolation() {
var interpolate = d3.scale.linear()
.domain([0,1])
.range([1, dataArray.length + 1]);
return function(t) {
var flooredX = Math.floor(interpolate(t));
var interpolatedLine = dataArray.slice(0, flooredX);
if(flooredX > 0 && flooredX < dataArray.length) {
var weight = interpolate(t) - flooredX;
var weightedLineAverage = dataArray[flooredX].y * weight + dataArray[flooredX-1].y * (1-weight);
interpolatedLine.push({"x":interpolate(t)-1, "y":weightedLineAverage});
//get the length of the path
var len = d3.select("#journey").node().getTotalLength();
//get the svg point at that length
var pt = d3.select("#journey").node().getPointAtLength(len);
//translate the circle to that point.
d3.select('#lineChart > #marker').attr("transform", "translate(" +pt.x + "," + pt.y + ")");
}
return lineFunction(interpolatedLine);
}
}
working code here
I am trying to learn using d3 chord diagram. Original script in http://bl.ocks.org/mbostock/1046712#index.html
But as I try to use the code locally I am getting TypeError: imports is undefined
My index.html has the following code. I have created a readme.json file with exact data form http://bl.ocks.org/mbostock/raw/1046712/readme.json
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
body {
font: 10px sans-serif;
}
.chord {
fill-opacity: .67;
}
</style>
<script>
function asd(){
alert("asd");
var outerRadius = 960 / 2,
innerRadius = outerRadius - 130;
var fill = d3.scale.category20c();
var chord = d3.layout.chord()
.padding(.04)
.sortSubgroups(d3.descending)
.sortChords(d3.descending);
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(innerRadius + 20);
var svg = d3.select("body").append("svg")
.attr("width", outerRadius * 2)
.attr("height", outerRadius * 2)
.append("g")
.attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
d3.json("readme.json", function(error, imports) {
var indexByName = d3.map(),
nameByIndex = d3.map(),
matrix = [],
n = 0;
// Returns the Flare package name for the given class name.
function name(name) {
return name.substring(0, name.lastIndexOf(".")).substring(6);
}
// Compute a unique index for each package name.
imports.forEach(function(d) {
if (!indexByName.has(d = name(d.name))) {
nameByIndex.set(n, d);
indexByName.set(d, n++);
}
});
// Construct a square matrix counting package imports.
imports.forEach(function(d) {
var source = indexByName.get(name(d.name)),
row = matrix[source];
if (!row) {
row = matrix[source] = [];
for (var i = -1; ++i < n;) row[i] = 0;
}
d.imports.forEach(function(d) { row[indexByName.get(name(d))]++; });
});
chord.matrix(matrix);
var g = svg.selectAll(".group")
.data(chord.groups)
.enter().append("g")
.attr("class", "group");
g.append("path")
.style("fill", function(d) { return fill(d.index); })
.style("stroke", function(d) { return fill(d.index); })
.attr("d", arc);
g.append("text")
.each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })
.attr("dy", ".35em")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + (innerRadius + 26) + ")"
+ (d.angle > Math.PI ? "rotate(180)" : "");
})
.style("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; })
.text(function(d) { return nameByIndex.get(d.index); });
svg.selectAll(".chord")
.data(chord.chords)
.enter().append("path")
.attr("class", "chord")
.style("stroke", function(d) { return d3.rgb(fill(d.source.index)).darker(); })
.style("fill", function(d) { return fill(d.source.index); })
.attr("d", d3.svg.chord().radius(innerRadius));
});
d3.select(self.frameElement).style("height", outerRadius * 2 + "px");
}
</script>
</head>
<body onload="asd()">
asd
</body>
</html>
I use apache in localhost.
One needs to set up a web server on a local machine in order to run such examples locally.
A good explanation is here.
I usually use python SimpleHTTPServer.
Also, you need to access your example via localhost:{port number}, not via file system.
There are few more gotchas, but I believe this would be sufficient for you to start.
This page needs to display a graph that reads the data from a CSV file.
I have been following a tutorial on TheCodingTutorials.
I'm also trying to follow the Multi-Column Data tutorial so that i can add the name to the graph. This is where i'm getting lost, the tutorial make it sound easy but i just don't get it. Every time i try to edit the code it errors out.
It works perfectly if you only want to read a single column csv file.
However I want to read a multiple columns csv file.
Also if there is something that could make it better please let me know.
<html>
<head>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
<html>
<head>
<meta http-equiv="Expires" content="-1">
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
{
d3.text("data2.csv", function(unparsedData)
{
var data = d3.csv.parseRows(unparsedData);
//Create the SVG graph.
var svg = d3.select("body").append("svg").attr("width", "100%").attr("height", "100%");
var dataEnter = svg.selectAll("rect").data(data).enter();
var graphHeight = 450;
var barWidth = 20;
var barSeparation = 10;
var maxData = 105;
var horizontalBarDistance = barWidth + barSeparation;
var textYOffset = horizontalBarDistance / 2 - 12;
var textXOffset = 20;
var barHeightMultiplier = graphHeight / maxData;
//Draw the bars.
dataEnter.append("rect").attr("y", function(d, i)
{
return i * horizontalBarDistance;
}).attr("x", function(d)
{
return 100;
}).attr("height", function(d)
{
return barWidth;
}).attr("width", function(d)
{
return d * barHeightMultiplier;
});
//Draw the text.
dataEnter.append("text").text(function(d)
{
return d;
}).attr("y", function(d, i)
{
return i * horizontalBarDistance + textXOffset;
}).attr("x");
});
};
}
</script>
</head>
<body onLoad="JavaScript:timedRefresh(10000);">
</body>
</html>
My CSV file now looks like this
names,data
john,78
brad,105
amber,103
james,2
dean,74
pat,45
matt,6
andrew,18
ashley,15
==================================================================================
UPDATE
==================================================================================
Thanks to all your help this is my updated code.
<html>
<head>
<meta http-equiv="Expires" content="-1">
<script type="text/javascript" src=".\JavaScripts\d3.v3.min.js"></script>
<script type="text/javascript">setTimeout(function(){window.location.href='index2.html'},120000);
d3.csv("./data/data.csv", function(data){
//Create the SVG graph.
var svg = d3.select("#graph").append("svg").attr("width", "1800").attr("height", "600");
var dataEnter = svg.selectAll("rect").data(data).enter();
var graphWidth = 800;
var barWidth = 40;
var barSeparation = 30;
var maxData = 2;
var horizontalBarDistance = barWidth + barSeparation;
var textYOffset = 25;
var barXOffset = 260;
var barYOffset = 5;
var numXOffset = 230;
var barHeightMultiplier = graphWidth / maxData;
var fontSize = "30px";
var color = d3.scale.category10();
//Draw the bars.
dataEnter.append("rect")
.attr("fill",function(d,i){return color(i);})
.attr("y", function(d, i){return i * horizontalBarDistance - barYOffset;})
.attr("x", barXOffset)
.attr("height", function(d){return barWidth;})
.attr("width", function(d){return d.data * barHeightMultiplier;});
//Draw the text.
dataEnter.append("text")
.text(function(d){return d.Name;})
.attr("font-size", fontSize)
.attr("font-family", "sans-serif")
.attr("y", function(d, i){return i * horizontalBarDistance + textYOffset;})
.attr("x");
//Draw the numbers.
dataEnter.append("text")
.text(function(d){return d.data;})
.attr("font-size", fontSize)
.attr("font-family", "sans-serif")
.attr("y", function(d, i){return i * horizontalBarDistance + textYOffset;})
.attr("x", numXOffset);
//Draw the Target bar
dataEnter.append("rect")
.attr("fill", "red")
.attr("y", function(d, i){return i * horizontalBarDistance;})
.attr("x", barXOffset + graphWidth)
.attr("height", 70)
.attr("width", 10);
});
</script>
<style type="text/css">
#title {
font-family:sans-serif;
font-size: 50px;
color:#000;
text-decoration: underline;
text-align: center;
width: 100%;
position:relative;
margin-top:20;
}
#graph {
overflow:hidden;
margin-top:40;
}
</style>
</head>
<body>
<div id="title">Graph 1</div>
<div id="graph"></div>
</body>
</html>
Because your data contains a header row as its first row, you should be using d3.csv.parse instead of d3.csv.parseRows. The CSV documentation explains the differences.
The result of parsing will be something that looks like this:
[
{"names": "john", "data": 78},
{"names": "brad", "data": 105},
...
]
So, when you use this data to create your rect elements, you get an object bound to each rect. Then when you use selection.attr or selection.style the d value you are passed will be the bound object. This means you will need to reference the property you want, either as d.names or d.data. Each column in the file will be a different property on the object (as shown above).
One other thing to consider is possibly replacing d3.text with d3.csv to retrieve the file and parse the data in one step.