Here is a picture of my problem
Every time try to refresh my d3js graph with new data, its x axis and y axis gets messed up with both old and new axis.In the picture on the y axis 3,2.5,2,1.5 .... was my old axis and 800,700,600.....was my new axis.Similarly with the x axis
Can any one tell me wat i'm doing wrong.I only want the new axis to show up.
Here is my d3js code.
function ShowGraph(data) {
var vis = d3.select("#visualisation"),
WIDTH = 500,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 30
},
xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(data, function (d) {
return d.year;
}),
d3.max(data, function (d) {
return d.year;
})]),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(data, function (d) {
return d.count;
}),
d3.max(data, function (d) {
return d.count;
})]),
xAxis = d3.svg.axis() // generate an axis
.scale(xRange) // set the range of the axis
.tickSize(5) // height of the ticks
.tickSubdivide(true), // display ticks between text labels
yAxis = d3.svg.axis() // generate an axis
.scale(yRange) // set the range of the axis
.tickSize(5) // width of the ticks
.orient("left") // have the text labels on the left hand side
.tickSubdivide(true); // display ticks between text labels
var transition = vis.transition().duration(1000).ease("exp-in-out");
transition.select(".x.axis").call(xAxis);
transition.select(".y.axis").call(yAxis);
vis.append("svg:g") // add a container for the axis
.attr("class", "x axis") // add some classes so we can style it
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")") // move it into position
.call(xAxis); // finally, add the axis to the visualisation
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var circles = vis.selectAll("circle").data(data)
circles.enter()
.append("svg:circle")
.attr("cx", function (d) {
return xRange(d.year);
})
.attr("cy", function (d) {
return yRange(d.count);
})
.style("fill", "red")
circles.transition().duration(1000)
.attr("cx", function (d) {
return xRange(d.year);
})
.attr("cy", function (d) {
return yRange(d.count);
})
.attr("r", 10)
circles.exit()
.transition().duration(1000)
.attr("r", 10)
.remove();
}
Here is it have a look. link Try with word "the,and,i,and,the" one at a time
Try to empty the axis before build the graph
function ShowGraph(data) {
d3.selectAll('.axis').remove();
var vis = d3.select("#visualisation"),
//...
EDIT
OK maybe I found the solution
The problem is the axis that appends every time to call the function.
So, if you add a check like so:
var hasAxis = vis.select('.axis')[0][0];
if(!hasAxis) {
vis.append("svg:g") // add a container for the axis
.attr("class", "x axis") // add some classes so we can style it
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")") // move it into position
.call(xAxis); // finally, add the axis to the visualisation
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
}
it should works
Related
I have a function where that when a button is pressed (Several buttons the represent several animal types), that animal types SVG is updated with its corresponding data. I'm trying to replicate this zoom function but am having issues implementing it with my code. There are several SVGs that are used globally like this (one for each animal type):
let x = d3.scaleLinear()
.domain([0, 1000])
.range([ 0, width ]);
var xAxis = d3.axisBottom(x);
svgReptile.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
const yAxis = d3.scaleLinear()
.domain([0, 220])
.range([ height, 0])
svgReptile.append("g")
.call(d3.axisLeft(yAxis))
The function below is called when one of the animal buttons is pressed.
function update(animal, whatSVG, xAxis, yAxis, color) {
const points = whatSVG
.selectAll("circle")
.data(data);
points.enter()
.append("circle")
.attr("cx", function(d) {
return xAxis(d.state);
})
.attr("cy", function(d) {
return yAxis(d.percentage);
})
.merge(points)
.attr("r", 3)
.attr("cx", function(d) {
return xAxis(d.decade)
})
.attr("cy", function(d) {
return yAxis(d.count)
})
.style("fill", function (d) { return colour(d.animal) } );
points.exit()
.attr('r', 0)
.remove();
}
Question:
How can I implement a zoom feature that expands the x-axis when zoomed (or anything similar) like the one linked above?
I think you're looking for a 'brush zoom' from the last line of your question.
The following source code if from an example in a d3 graph gallery
The cross hair allows you to select an area to expand. If you follow the link there is a graph above it that is entitled "Zoom with axis" but it doesn't zoom in the way you've described, it just moves the axis, but doesn't enlarge the graph contents with it. Perhaps both will be useful!
Hope this helps
// set the dimensions and margins of the graph
var margin = {top: 10, right: 20, bottom: 20, left: 20},
width = 500 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
var Svg = d3.select("#brushZoom")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
//Read the data
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {
// Add X axis
var x = d3.scaleLinear()
.domain([4, 8])
.range([ 0, width ]);
var xAxis = Svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, 9])
.range([ height, 0]);
Svg.append("g")
.call(d3.axisLeft(y));
// Add a clipPath: everything out of this area won't be drawn.
var clip = Svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("width", width )
.attr("height", height )
.attr("x", 0)
.attr("y", 0);
// Color scale: give me a specie name, I return a color
var color = d3.scaleOrdinal()
.domain(["setosa", "versicolor", "virginica" ])
.range([ "#440154ff", "#21908dff", "#fde725ff"])
// Add brushing
var brush = d3.brushX() // Add the brush feature using the d3.brush function
.extent( [ [0,0], [width,height] ] ) // initialise the brush area: start at 0,0 and finishes at width,height: it means I select the whole graph area
.on("end", updateChart) // Each time the brush selection changes, trigger the 'updateChart' function
// Create the scatter variable: where both the circles and the brush take place
var scatter = Svg.append('g')
.attr("clip-path", "url(#clip)")
// Add circles
scatter
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function (d) { return x(d.Sepal_Length); } )
.attr("cy", function (d) { return y(d.Petal_Length); } )
.attr("r", 8)
.style("fill", function (d) { return color(d.Species) } )
.style("opacity", 0.5)
// Add the brushing
scatter
.append("g")
.attr("class", "brush")
.call(brush);
// A function that set idleTimeOut to null
var idleTimeout
function idled() { idleTimeout = null; }
// A function that update the chart for given boundaries
function updateChart() {
extent = d3.event.selection
// If no selection, back to initial coordinate. Otherwise, update X axis domain
if(!extent){
if (!idleTimeout) return idleTimeout = setTimeout(idled, 350); // This allows to wait a little bit
x.domain([ 4,8])
}else{
x.domain([ x.invert(extent[0]), x.invert(extent[1]) ])
scatter.select(".brush").call(brush.move, null) // This remove the grey brush area as soon as the selection has been done
}
// Update axis and circle position
xAxis.transition().duration(1000).call(d3.axisBottom(x))
scatter
.selectAll("circle")
.transition().duration(1000)
.attr("cx", function (d) { return x(d.Sepal_Length); } )
.attr("cy", function (d) { return y(d.Petal_Length); } )
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<div id="brushZoom"></div>
This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 4 years ago.
I'm getting introduced to javascript and I'm trying to use .on("mouseovert", ...) in order to get the x-value of my graph when the cursor is upon the graph.
My code look like this:
// do something as mouseover the graph
svg.select("svg")
.on("mouseover", alert("mouse on graph"));
The result is: an alert appears when I open the html file (and loading my js script), but nothing happen as is hover the graph.
Everything else in the script works fine.
Do you know why?
Thank you very much for the time you take!
Here is the full script:
function draw_co2(url) {
d3.select("svg").remove() //remove the old graph
// set the dimensions and margins of the graph
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// parse the date / time
var parseTime = d3.timeParse("%Y-%m-%d");
// Get the data
d3.json(url, function (error, data) {
if (error)
throw ('There was an error while getting geoData: ' + error);
data.forEach(function (d) {
d.Date = parseTime(d.Date);
d.Trend = +d.Trend;
});
// set the ranges // Scale the range of the data
var x = d3.scaleTime().domain([new Date("1960"), new Date("2015")]).range([0, width]);
var y = d3.scaleLinear()
.domain([d3.min(data, function (d) {
return d.Trend;
}) - 1 / 100 * d3.min(data, function (d) {
return d.Trend;
}), d3.max(data, function (d) {
return d.Trend;
}) + 1 / 100 * d3.min(data, function (d) {
return d.Trend;
})])
.range([height, 0]);
// define the line
var valueline = d3.line()
.x(function (d) {
return x(d.Date);
})
.y(function (d) {
return y(d.Trend);
});
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#graph_draw").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
//Y Axis label
svg.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Carbon dioxide (ppm)");
// Add the valueline path.
svg.append("path")
.data([data])
.style("opacity", 0)
.transition()
.duration(1000)
.style("opacity", 1)
.attr("class", "line")
.attr("d", valueline);
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
// gridlines in x axis function
function make_x_gridlines() {
return d3.axisBottom(x)
.ticks(10);
};
// add the X gridlines
svg.append("g")
.attr("class", "grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_gridlines()
.tickSize(-height)
.tickFormat(""));
// do something as mouseover the graph
svg.select("svg")
.on("mouseover", alert("mouse on graph"));
})
}
Use mouser over as an inline function
svg.select("svg")
.on("mouseover", function () {
alert("mouse on graph")
});
I have been developing an area chart for year(x axis) vs Revenue (y axis) in D3 Js.The data is as:
localData=[
{"Revenue":"4.5","Year":"2011"},
{"Revenue":"5.5","Year":"2010"},
{"Revenue":"7.0","Year":"2012"},
{"Revenue":"6.5","Year":"2013"}
]
I want year at x axis and revenue at y axis for an area chart.Currently I am using time scale for x axis but i dont know how to use it as I have not date format I have only Years to represent.
My Current code is:
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 500 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var area = d3.svg.area()
.x(function (d) { return x(d.Year); })
.y0(height)
.y1(function (d) { return y(d.Revenue); });
$("#chartArea").html("");
var svg = d3.select("#chartArea").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.extent(localData, function (d) { return d.Year; }));
y.domain([0, d3.max(localData, function (d) { return d.Revenue; })]);
svg.append("path")
.datum(localData)
.attr("class", "area")
.attr("d", area)
.attr("fill",color);
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("Revenue (M)");
Currently I am getting on my X axis as .011,.012,013,.014 I need as 2011,2012,2013,2014
I am new to D3 js so dnt know much about how to use scales??Please Help anyone..Thanks in advance.
Just add tick Format to your x Axis definition:
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%Y")); // <-- format
In v4, it'd be something like this:
d3.axisBottom(x).ticks(d3.timeYear.every(1))
huan feng is right. The time scale is treating your year(implicitly converted to an int) as timestamps. To force the scale to operate on the year, create Date objects specifying the year in it. Basically change the following line:
x.domain(d3.extent(localData, function (d) { return d.Year; }));
to
x.domain(d3.extent(localData, function (d) { return new Date(parseInt(d.Year),0); }));
You may then use Klaujesi's solution to change the tickFormat.
I have a plot which are is small in size in my home page and when i click on the plot, i want it to open the plot in an enlarged size in a new tab.
I tried the following, but its just opening a new tab but did not plot anything.
Assume that vis is the element that contains the current plot and when vis is clicked, it should plot the same graph bigger in a new window.
The max value,data and date_array are all printed correctly, so there is no problem with the data.
vis.on('click', function(){
var newWindow = window.open('');
console.log(data[0]);
console.log(date_array);
console.log(max_value);
var vis1 = d3.select(newWindow.document.body),
WIDTH = 400,
HEIGHT = 150,
MARGINS = {
top: 10,
right: 10,
bottom: 10,
left: 100
},
xScale = d3.scale.ordinal().domain(date_array).rangePoints([MARGINS.left, WIDTH - MARGINS.right]),
yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0, max_value]),
xAxis = d3.svg.axis()
.scale(xScale)
yAxis = d3.svg.axis()
.scale(yScale);
vis1.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis)
vis1.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis)
var lineGen = d3.svg.line()
.x(function(d) {
return xScale(d.count);
})
.y(function(d) {
return yScale(d.param_perc);
})
.interpolate("basis");
vis1.append('svg:path')
.attr('d', lineGen(data))
.attr('stroke', color)
.attr('stroke-width', 2)
.attr('fill', 'none')
})
In order to plot an svg you first need to insert an svg. Your code is appending gs and a path to the body but it is missing the containing svg element. This could easily be solved by adding
vis1 = vis1.append("svg");
This works for me in a boiled down Plunk.
So I'm dynamically creating a bunch of simple line charts with D3 and everything is going well, but for some reason charts with ranges that go from 9-10 get inverted and look absolutely terrible/do not function properly.
the first one, the values are upside down
this one is fine...
Here is some code...
var dataRange = d3.extent(quoteObjects, function(d){ return d.close });
var dateRange = d3.extent(quoteObjects, function(d){ return d.date });
// Set chart variables
var vis = d3.select("#"+type),
WIDTH = $('#chart-box').width(),
HEIGHT = $('#'+type).innerHeight(),
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 60,
},
// set scales
xScale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]).domain(dateRange),
yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain(dataRange),
// create displayed axis
xAxis = d3.svg.axis()
.scale(xScale)
.tickValues( xScale.ticks(6) )
yAxis = d3.svg.axis()
.scale(yScale)
.tickValues( yScale.ticks(6) )
.orient("left");
console.log("WH", WIDTH, HEIGHT);
if (type == "intraday"){
xAxis.tickFormat(d3.time.format("%H"))
}
// append x axis
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.top) + ")")
.call(xAxis);
// append y axis
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
// create line based on "close" values
var lineGen2 = d3.svg.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.close);
})
.interpolate("basis");
// append "close" line
vis.append('svg:path')
.attr('d', lineGen2(quoteObjects))
.attr('stroke', '#931a28')
.attr('stroke-width', 3)
.attr('fill', '#222');