score:1
Accepted answer
Indeed you have an issue with your scope. The variable data is defined inside a function, so it can't be available out of this function. Here is the code to make it works :
<!DOCTYPE html>
<meta charset="utf-8">
<style type="text/css">
body {
font-family: avenir next, sans-serif;
font-size: 12px;
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
.axis {
stroke-width: 0.5px;
stroke: #888;
font: 10px avenir next, sans-serif;
}
.axis>path {
stroke: #888;
}
</style>
<body>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {
top: 20,
right: 20,
bottom: 90,
left: 50
},
margin2 = {
top: 230,
right: 20,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom,
height2 = 300 - margin2.top - margin2.bottom;
var x = d3.scaleBand().range([0, width]).padding(0.1),
x2 = d3.scaleBand().range([0, width]).padding(0.1),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x).tickSize(0),
xAxis2 = d3.axisBottom(x2).tickSize(0),
yAxis = d3.axisLeft(y).tickSize(0);
var brush = d3.brushX()
.extent([
[0, 0],
[width, height2]
])
// .on("start brush end", brushed);
.on("brush", brushed);
var zoom = d3.zoom()
.scaleExtent([1, 2])
.translateExtent([
[0, 0],
[width, height]
])
.extent([
[0, 0],
[width, height]
])
.on("zoom", zoomed);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
focus.append("text") // yAxis label
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Distance in meters");
svg.append("text") // xAxis label
.attr("transform",
"translate(" + ((width + margin.right + margin.left) / 2) + " ," +
(height + margin.top + margin.bottom) + ")")
.style("text-anchor", "middle")
.text("Date");
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom); //see var zoom above
focus.append("g") //append xAxis to main chart
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var data_global=null;
d3.json("data.json", function(error, data) {
if (error) throw error;
data_global=data;
focus.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.distance;
})])
.range([height, 0])).tickSize(0));
data.forEach(function(d) {
d.distance = +d.distance;
return d;
},
function(error, data) {
if (error) throw error;
});
x.domain(data.map(function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.distance;
})]);
x2.domain(x.domain());
y2.domain(y.domain());
//********* Main ar Chart ****************
var rects = focus.append("g");
rects.attr("clip-path", "url(#clip)");
rects.selectAll("rects")
.data(data)
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rects")
.attr("x", function(d) {
return x(d.date);
})
.attr("y", function(d) {
return y(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.distance);
});
// //********* Brush Bar Chart ****************
var rects = context.append("g"); //draw bar chart in brush
rects.attr("clip-path", "url(#clip)");
rects.selectAll("rect")
.data(data)
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rectss")
.attr("x", function(d) {
return x2(d.date);
})
.attr("y", function(d) {
return y2(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height2 - y2(d.distance);
});
context.append("g")
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
}); //closes d3.json()
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
// get bounds of selection
var s = d3.event.selection,
nD = [];
x2.domain().forEach((d) => { //not as smooth as I'd like it
var pos = x2(d) + x2.bandwidth() / 2;
if (pos > s[0] && pos < s[1]) {
nD.push(d);
}
});
x.domain(nD);
focus.selectAll(".rects")
.remove().exit()
.data(data_global.filter(function(d) {
return nD.indexOf(d.date) > -1
}))
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rects")
.attr("x", function(d) {
return x(d.date);
})
.attr("y", function(d) {
return y(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.distance);
});
focus.select(".x-axis").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
};
function zoomed() {};
</script>
Source: stackoverflow.com
Related Query
- D3.js scope issue with external data.json file and brush
- get data from external json with react and d3
- How to load data from an internal JSON array rather than from an external resource / file for a collapsible tree in d3.js?
- Difficulty accessing json file with d3 and flask
- javascript d3.js: initialize brush with brush.extent and stop data from spilling over margin
- Create an interactive 3d scatter plot with D3.js and Three.js with json data
- Using D3.js with a javascript object instead of an external JSON file
- D3 Visualization of network data (nodes and links) via json file
- How can i bind an json data with a key and Name for display
- How to use the quantize function with my json data file
- Javascript d3 pie chart doesn't pull data from JSON file with list of dictionaries
- How do you get JSON data and create a line chart with d3.js?
- Time in x-axis and data for the y-axis for line chart in d3.js doesn't match/show with what (data) is on JSON
- How do I configure Ghost in in dev and production to make a json data available via url to load with d3.json?
- "Cannot read property 'length' of null" with Angular-cli and a json file
- D3 JSON file with source and index as strings rather than indices
- Formatting data for use with JSON and D3.js
- How to modify tags of an already existing svg object with data from json file
- D3 - V3: Scope error when using data loaded from a json file
- Problems making radial gradient in arcs using javascript, d3 with data from json file
- Can we add images in json data file and call it on page using D3.js
- Feeding data into database with Php form and using that data into JSON format to be used in D3
- Populating D3 chart with external JSON file
- Append multiple external svg in d3 and bind them with data
- How do I use JSON and return data with D3
- Loading internal JSON data rather than from an external resource / file for a sunburst in d3
- JSON data undefined from external file in d3.js?
- D3.js horizontal bar chart and data from json file
- Plotting data from json file with different date format
- JavaScript d3 line graph with ordinal axis and json data
More Query from same tag
- D3 Code Is Creating 2 SVG elements in the div
- How does this moving average functions work?
- d3.js t.map is not a function
- Unexpected value NaN parsing cy attribute
- Draw d3-axis with react, without direct D3 DOM manipulation
- D3.js: Understanding Zoom in terms of svg
- Add text after last node in D3 Sankey diagram
- CoffeeScript methods as D3js callbacks
- How to load txt files into D3.JS
- Updating the column type of a large dataset in d3.js
- Log scale on D3.js
- loading json file to d3.js
- How to get a single property of all children in a nested object using javascript?
- d3-drag with html elements initial position issue
- Ionic D3.js piechart does not render
- How to modify the scale of a radar chart from percent to numeric values
- d3-fetch and UTF-16 LE
- How to create a gradient that goes across different rectangles in D3JS?
- d3.js - maintain interaction with use of canvas
- D3 2 dimensional brush not slideable
- D3 rendering map not completely
- Fire event during a transition
- How to get biggest array element based on his second sub array value
- d3.js throws an error 't.slice is not a function'
- D3 trouble parsing CSV file
- Push R matrix to D3 to create an animated ellipse chart
- How to properly add and use D3 Events?
- tooltip for a scatter plot matrix - using d3
- Background image to bubble chart
- How to scale bars of barchart so it shows the complete graph with data