score:0
d3.csv("data2.csv", function(error, data) {
if your server is caching this reference - try a Math.random()
:D
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
This will force(ish) a refresh of data - could be costly so triage according to your needs via a serverside process
edit:
d3.csv("data2.csv?=" + (Math.random() * (100 - 1) + 1), function(error, data) {
would be the alteration. Its sloppy but illustrates how to suggestively force a cache refresh
score:0
You can do it like this:
Make a buildMe()
function which makes the graph.
function buildMe(file) {//the file name to display
d3.csv(file, function(error, data) {
if (error) throw error;
var ageNames = d3.keys(data[0]).filter(function(key) {
return key !== "State";
});
data.forEach(function(d) {
d.ages = ageNames.map(function(name) {
return {
name: name,
value: +d[name]
};
});
});
x0.domain(data.map(function(d) {
return d.State;
}));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) {
return d3.max(d.ages, function(d) {
return d.value;
});
})]);
svg.selectAll("g").remove();//remove all the gs within svg
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) {
return "translate(" + x0(d.State) + ",0)";
});
state.selectAll("rect")
.data(function(d) {
return d.ages;
})
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) {
return x1(d.name);
})
.attr("y", function(d) {
return y(d.value);
})
.attr("height", function(d) {
return height - y(d.value);
})
.style("fill", function(d) {
return color(d.name);
});
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 20 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) {
return d;
});
});
}
Then on Load do this buildMe("data.csv");
On button click do this
function updateMe() {
console.log("Hi");
buildMe("data2.csv");//load second set of data
}
Working code here
Hope this helps!
score:1
You say you want to update an existing graph with your update function and new data coming from an csv after some event occurs, correct?
D3 stands for Data Driven Documents, so your data is very important when drawing graphs. D3 works with selections (or collections if that works better for you) based on the data you want to display.
Say you want a barchart displaying the following array: [10,20,30]. The height of the bars is in function with the data in the array.
creating new elements
If you dont have bar elements on the page already, that means you will need to 'append' them to the graph. This is usually done with a code pattern resembling like:
svg.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
With this code, you take the svg variable (which is basically a d3 selection containing one element, the svg) and you select all "rect" elements on the page but inside the svg element. There are none at this very moment, remember, you are going to create them. After the selectAll, you see the data function which specifies the data that will be bound to the elements. Your array contains 3 pieces of data, that means that you expect ot see 3 bars. How will D3 know? It will because of the .enter() (meaning: which elements are not on the graph yet?) and the .append(element) functions. The enter function basically means: In my current d3 selection (being selecAll('rect') ), how many of the specified elements do i need to append? Since you current selection is empty (you dont have 'rect' elements yet), and d3 spots 3 pieces of data in your data function, using .append() it will create and append 3 elements for you. With the attr fuctions you can specify how the elements will look like.
updating elements
Suppose my array of [10,20,30] suddenly changes to [40,50,60]. notice something very important here, my array still contains 3 pieces of data! It is just their value that changed!
I would really want to see my bars reflecting this update! (and i think your case matches this one).
But if I use this pattern again, what will happen?
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
...
The state.selectAll("rect") selection contains 3 elements, d3 checks how many pieces of data you have (still 3) and it sees that it doesnt need to append anything!
Does that mean you cannot update with D3? Absolutely not! It is just much simpler then you would think :-).
If i would want to update my bars so that their height reflects the new values of my data, I should do it like this:
state.selectAll("rect")
.data(function(d) { return d.ages; })
.attr("height", function(d) { return height - y(d.value); });
Basically, I select all my rects, I tell d3 what data i am working on and then I simply tell d3 to alter the height of of my rect. You can even do it with a transition! (more info on transitions here ). I think this is what you need to do, instead of appending the "rect" elements again.
Updating elements, part 2
continuing with my example, what do to if my array all of a sudden wouuld be like this: [100,200,300, 400]? Note that my values changed again BUT there is an extra element there!!
Well, when handling the event (for example a click on a button, or a submit of data) that changes the data, you need to tell D3 that it will need to append something and update the existing bars. This can simply be done by doing coding both patterns:
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.attr("height", function(d) { return height - y(d.value); });
Removing elements
What if my data array would suddenly only consist of only 2 pieces of data: [10,20] ?
Just like there is a function for telling d3 that it needs to append something, you can tell it that it what to do with elements that dont seem to have data to be bound on anymore:
svg.selectAll("rect")
.data(function(d) { return d.ages; })
.exit().remove();
The exit function matches the amount of pieces of data you have vs the amount of selected elements. The exit function then tells d3 to drop those elements.
I hope this was helpfull. It is a bit of a basic explanation (its a little more complicated then that) but I had to hurry, so if there should be questions or errors, please tell me.
Source: stackoverflow.com
Related Query
- D3JS refreshing graph for new Data
- d3js graph retaining old axis data on refreshing with new data
- d3js graph code showing y axes in different order for different data
- How to change randomised data used for graph values with my input data? D3js donut graph
- Is D3.js the right choice for real-time visualization of Neo4j Graph DB data
- Direct data input from Django for a D3 graph
- Data for sunburst charts with d3.hierarchy using D3js v4
- What's the best force-directed network graph engine for large data sets?
- D3js code when called twice duplicates the graph instead of refreshing
- Accessing nested data for graph creation
- How to convert table data to nodes and links for d3js Sankey
- grouping of data for focus and context graph - d3.js
- d3.js - How to do data mapping and filter for Stacked Bar graph
- Update d3 graph with new data
- d3.js not updating graph with new data
- Redraw d3 graph with a new data
- D3 Data Loading For A Choropleth Graph or Heat Map
- D3js button onclick function to zoom the graph for specific timeframe
- D3.JS bar graph column offset while adding new data
- Gathering some data for a network graph in D3. How should I format it?
- How can D3js pack layout use data join by key for updates?
- Plotting a graph in a new tab using onclick of d3js
- D3js - Reuse line definition/function for multiple data categories in file
- Bind only new data points for performance optimization
- Fitting data for D3 graph to create legend
- D3JS Plotting Line Graph From Array Data (Data is undefined error)
- how can i group JSON data and generate a graph of each group in D3js
- d3 v4 getting data for bar graph tooltip
- Loading data from MySQL to use in D3 for creating line graph
- Rendering new graph data adds new graph instead of replacing existing one
More Query from same tag
- Import EventDrops (D3.js) into Angular 2
- Disable SVG autoscaling proportionally
- run d3.js with local JSON file
- Understanding D3 data binding key accessor
- How to tweak d3 axis attributes when transition is present?
- Circle packs as nodes of a D3 force layout
- How to change the order of grouped bar chart in dimple?
- d3 creating A multiseries chart using d3
- Possible d3 Bug: dragend fires without any drag event
- How to label one specific scatter point (not all points) using d3 or regular javascript?
- How do I benchmark an algorithm implemented in D3?
- How to repaint my nodes? D3.js
- Multi-series bar chart in DC-js
- NVD3.js Loading line data from JSON
- Problems with parsing JSON for D3
- csv data to nested json tree in d3
- Google map does not display
- Angular NVD3 Multibar Chart with dual y-axis to showup only line using json data
- d3 bind element to data points / data values
- Filtering Data with on click function
- Issues with preserveAspectRatio, viewBox and layout.size()
- d3 path: Why are square brackets used in .data([...])
- placing d3 label at end of arc
- Can't access data in D3 within on click event?
- Failure rendering foreignObject inside SVG leveraging d3
- Date Ticks or String ticks as xAxis for line chart in d3
- can't get .exit() and .enter() to work properly when updating data in d3.js
- D3.js: real-time sunburst Partition data: recreate Hierarchy?
- force layout set fixed distance each nodes even after dragging
- d3 sorting of an array of objects