I have a scatter plot graph in my reactJS app using d3 and svg. I need to display horizontal lines on y-axis below the labels. Currently, the horizontal lines are appearing beside the labels.
here's my code:
const yAxis = d3.axisLeft(yScale).tickFormat(function(d) {
if (d != minYFloor)
return d + " yds";
else return "";
})
.tickSize(-width - 20, 0, 0);
tickSize function in above code renders horizontal lines in the graph like this:
This is my css:
.axisY line {
fill: none;
stroke: #fff;
opacity: 0.3;
shape-rendering: crispEdges;
}
While I need something like this:
How do I go about achieving that?
Here is a basic example of how you can translate the ticks in the axis.
Let's suppose this running snippet:
var svg = d3.select("svg");
var scale = d3.scalePoint()
.domain([0, 50, 100, 150, 200])
.range([140, 10]);
var axis = d3.axisLeft(scale)
.tickFormat(function(d) {
return d + " yds"
})
.tickSize(-250);
var g = svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(50,0)")
.call(axis);
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
As you can see, it's a common y axis, just like yours.
To translate the ticks we first assign that axis'group a specific class (or ID):
.attr("class", "axis")
Then, we select the texts with the ticks class, and move them:
svg.selectAll(".axis .tick text")
.style("text-anchor", "start")
.attr("transform", "translate(4,-6)")
Here is the demo:
var svg = d3.select("svg");
var scale = d3.scalePoint()
.domain([0, 50, 100, 150, 200])
.range([140, 10]);
var axis = d3.axisLeft(scale)
.tickFormat(function(d) {
return d + " yds"
})
.tickSize(-250);
var g = svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(50,0)")
.call(axis);
svg.selectAll(".axis .tick text")
.style("text-anchor", "start")
.attr("transform", "translate(4,-6)")
.axis path {
stroke: none;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
Here I'm using magic numbers, change them accordingly.
Finally, there is an important advice: unlike what your question's title suggest, move the labels, not the lines. The lines are the actual indicator of the position to the users seeing the datavis.
Related
Im creating a line chart graph using d3 js. I need a solution to change the y scale values when I resize the window instead of scroll bar.
I have added the code below which adds scroll bar when I resize the screen size. I want design dynamic y scale values when we resize for different screen sizes.
`
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
body { font: 12px Arial;}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
// Adds the svg canvas
var svg = d3.select("body")
.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 + ")");
// Get the data
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
});
</script>
</body>
`
A method I like to use is to wrap the code in a function (lets call it main()), and re-run when the screen size changes.
At the beginning of this new main() function, remove the old (and now redundantly sized) svg.
d3.select("#<id of svg>").remove();
Then, create the new y scale using
var new_width = document.getElementById("<Div ID>").clientWidth;
var new_height = document.getElementById("<Div ID>").clientHeight;
and apply these to the new svg as you create it. D3 should allow you to run the .remove() line before the initial svg has been created. Make sure to then add an id when you create the svg (using attr("id", "<id of svg>")).
After that, you can call the main() function on resizing with
d3.select(window).on( "resize", main() );
The way in which you want to actually size your Div will now rely on your CSS, so you can use something like {height:50vh} or whatever you like.
Hope this helps.
P.S. By the way, why are you using D3 version 3? We're up to v5 :)
I am working on creating a horizontal bar chart using D3 in a ReactJS application. The issue I'm having is that the bars are too long and get cut off. How can I scale the bars down proportionally?
Appreciate any advice.
If you want to fit your chart then you need to change width/height of container where your chart is rendered (see <svg> in code below). Usually bars maximum height or width must not exceed correspondent container's dimension size, so probably you have an error somewhere in code. It would be helpful if you could share your code.
Here I provide an example of horizontal bar chart that scales correctly (original: https://bl.ocks.org/caravinden/eb0e5a2b38c8815919290fa838c6b63b):
var data = [{"salesperson":"Bob","sales":33},{"salesperson":"Robin","sales":12},{"salesperson":"Anne","sales":41},{"salesperson":"Mark","sales":16},{"salesperson":"Joe","sales":159},{"salesperson":"Eve","sales":38},{"salesperson":"Karen","sales":21},{"salesperson":"Kirsty","sales":25},{"salesperson":"Chris","sales":30},{"salesperson":"Lisa","sales":47},{"salesperson":"Tom","sales":5},{"salesperson":"Stacy","sales":20},{"salesperson":"Charles","sales":13},{"salesperson":"Mary","sales":29}];
// set the dimensions and margins of the graph
var
svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 60},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
// set the ranges
var y = d3.scaleBand()
.range([height, 0])
.padding(0.1);
var x = d3.scaleLinear()
.range([0, width]);
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
svg = svg
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// format the data
data.forEach(function(d) {
d.sales = +d.sales;
});
// Scale the range of the data in the domains
x.domain([0, d3.max(data, function(d){ return d.sales; })])
y.domain(data.map(function(d) { return d.salesperson; }));
//y.domain([0, d3.max(data, function(d) { return d.sales; })]);
// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
//.attr("x", function(d) { return x(d.sales); })
.attr("width", function(d) {return x(d.sales); } )
.attr("y", function(d) { return y(d.salesperson); })
.attr("height", y.bandwidth());
// 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));
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis--x path {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<svg width="300" height="500"></svg>
I am trying to have two (or more) similiar graph on one page inside an Ionic2 app. I use d3-ng2-service for wrapping the d3 types for Angular2. My problem is the following: When I try to place the two graphs in two different div elements each inside their respective custom element the drawing fails for both. When I did select the first div in the page the second graph overrides the first one, but it does get drawn.
Is there a clever way to place graphs more the the one graph? The examples always give the outer container a unique id, which is, what I try to do too:
import { Component, Input, OnInit, ElementRef } from '#angular/core';
import { D3Service, D3, Selection, ScaleLinear, ScaleTime, Axis, Line } from 'd3-ng2-service'; // <-- import the D3 Service, the type alias for the d3 variable and the Selection interface
#Component({
selector: 'd3-test-app',
templateUrl: 'd3-test-app.html',
providers: [D3Service],
})
export class D3TestAppComponent {
//Time is on x-axis, value is on y-axis
#Input('timeSeries') timeSeries: Array<{isoDate: string | Date | number | {valueOf(): number}, value: number}>;
#Input('ref') ref: string;
/* the size input defines, how the component is drawn */
#Input('size') size: string;
private d3: D3;
private margin: {top: number, right: number, bottom: number, left: number};
private width: number;
private height: number;
private d3ParentElement: Selection<any, any, any, any>; // <-- Use the Selection interface (very basic here for illustration only)
constructor(element: ElementRef,
d3Service: D3Service) { // <-- pass the D3 Service into the constructor
this.d3 = d3Service.getD3(); // <-- obtain the d3 object from the D3 Service
this.d3ParentElement = element.nativeElement;
}
ngOnInit() {
let x: ScaleTime<number, number>;
let y: ScaleLinear<number, number>;
let minDate: number;
let maxDate: number;
let minValue: number = 0;
let maxValue: number;
// set the dimensions and margins of the graph
switch (this.size) {
case "large":
this.margin = {top: 20, right: 20, bottom: 30, left: 50};
this.width = 640 - this.margin.left - this.margin.right;
this.height = 480 - this.margin.top - this.margin.bottom;
break;
case "medium":
this.margin = {top: 20, right: 0, bottom: 20, left: 20};
//golden ratio
this.width = 420 - this.margin.left - this.margin.right;
this.height = 260 - this.margin.top - this.margin.bottom;
break;
case "small":
this.margin = {top: 2, right: 2, bottom: 3, left: 5};
this.width = 120 - this.margin.left - this.margin.right;
this.height = 80 - this.margin.top - this.margin.bottom;
break;
default:
this.margin = {top: 20, right: 20, bottom: 30, left: 50};
this.width = 640 - this.margin.left - this.margin.right;
this.height = 480 - this.margin.top - this.margin.bottom;
}
// ...
if (this.d3ParentElement !== null) {
let d3 = this.d3; // <-- for convenience use a block scope variable
//THIS FAILS...
let selector: string = '#' + this.ref + ' .graphContainer';
console.log(selector);
let svg = d3.select( selector).append("svg")
.attr("width", this.width + this.margin.left + this.margin.right)
.attr("height", this.height + this.margin.top + this.margin.bottom)
.append("g")
.attr("transform",
"translate(" + this.margin.left + "," + this.margin.top + ")");
this.timeSeries.forEach((d) => {
d.isoDate = +d3.isoParse(d.isoDate as string);
d.value = +d.value;
if (minDate == null || minDate >= d.isoDate) {
minDate = d.isoDate as number;
}
if (maxDate == null || maxDate <= d.isoDate) {
maxDate = d.isoDate as number;
}
// if (minValue == null || minValue >= d.value) {
// minValue = d.value as number;
// }
if (maxValue == null || maxValue <= d.value) {
maxValue = d.value as number;
}
});
// TODO magic numbers to real min max
x = d3.scaleTime().domain([minDate, maxDate]).range([0,this.width]);
y = d3.scaleLinear().domain([0, maxValue]).range([this.height, 0]);
let xAxis: Axis<number | Date | {valueOf() : number;}> = d3.axisBottom(x);
let yAxis: Axis<number | {valueOf(): number;}> = d3.axisLeft(y);
let valueLine: Line<{isoDate: number; value: number}> = d3.line<{ isoDate: number; value: number }>()
.x(function (d) { return x(d.isoDate)})
.y(function (d) { return y(d.value)});
// Add the valueline path.
svg.append("path")
.data([this.timeSeries as {isoDate: number, value: number}[]])
.attr("class", "line")
.attr("d", valueLine);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + this.height + ")")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
}
}
myParser() : (string) => Date {
return this.d3.utcParse("%Y-%m-%dT%H:%M:%S.%LZ");
}
}
The HTML:
<div class='graphContainer'>
</div>
The HTML file where the custom component is used:
<ion-header>
<ion-navbar #dashboardNav>
<ion-title>Dashboard</ion-title>
<button ion-button menuToggle="favMenu" right>
<ion-icon name="menu"></ion-icon>
</button>
</ion-navbar>
</ion-header>
<ion-content>
<ion-item *ngFor="let entry of dashboard">
{{ entry.name }}
<d3-test-app [id]='entry.name' [timeSeries]='entry.timeSeries' [ref]='entry.name' size='medium'></d3-test-app>
</ion-item>
</ion-content>
Hard to debug without seeing a stack trace but it looks like this is failing because of how you select the element. I will base my answer on that assumption.
Querying by ID is handy when you have to look inside the DOM for a specific element and when you are sure there is only one element with that ID. Since you are inside an Angular element you already have the reference you need, it's the element itself, no need to dynamically create ID references.
I am not an expert in ng2 at all, but take a look a at how to select the raw element in Angular and choose the best approach for the framework. Say you go for something like the example shown on this answer:
constructor(public element: ElementRef) {
this.element.nativeElement // <- your direct element reference
}
NB - looks like there are various way of achieving this... not sure this is the best/correct one, but the goal is to get the ref anyway
Then simply select it via the D3 dsl like you are already doing by passing that raw reference
// At this point this.element.nativeElement
// should contain the raw element reference
if (this.d3ParentElement !== null) {
const { d3, element } = this; // <-- for convenience use block scope variables
const svg = d3.select(element.nativeElement).append("svg")...
I have an area graph ( see js fiddle https://jsfiddle.net/o7df3tyn/ ) I want to animate this area graph. I tried the approach in this
question , but this doesnt seem to help because I have more line graphs in the the same svg element
var numberOfDays = 30;
var vis = d3.select('#visualisation'),
WIDTH = 1000,
HEIGHT = 400,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
};
var drawArea = function (data) {
var areaData = data;
// var areaData = data.data;
var xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([0, numberOfDays + 1]),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([_.min(areaData), _.max(areaData)]);
var area = d3.svg.area()
.interpolate("monotone")
.x(function(d) {
return xRange(areaData.indexOf(d));
})
.y0(HEIGHT)
.y1(function(d) {
return yRange(d);
});
var path = vis.append("path")
.datum(areaData)
.attr("fill", 'lightgrey')
.attr("d", area);
};
var data = [1088,978,1282,755,908,1341,616,727,1281,247,1188,11204,556,15967,623,681,605,7267,4719,9665,5719,5907,3520,1286,1368,3243,2451,1674,1357,7414,2726]
drawArea(data);
So I cant use the curtain approach.
I want to animate the area from bottom.
Any ideas / explanations ?
Just in case anyone else stuck in the same problem, #thatOneGuy nailed the exact problem. My updated fiddle is here https://jsfiddle.net/sahils/o7df3tyn/14/
https://jsfiddle.net/DavidGuan/o7df3tyn/2/
vis.append("clipPath")
.attr("id", "rectClip")
.append("rect")
.attr("width", 0)
.attr("height", HEIGHT);
You can have a try now.
Remember add clip-path attr to the svg elements you want to hide
In this case
var path = vis.append("path")
.datum(areaData)
.attr("fill", 'lightgrey')
.attr("d", area)
.attr("clip-path", "url(#rectClip)")
Update:
If we want to grow the area from bottom:
vis.append("clipPath")
.attr("id", "rectClip")
.append("rect")
.attr("width", WIDTH)
.attr("height", HEIGHT)
.attr("transform", "translate(0," + HEIGHT + ")")
d3.select("#rectClip rect")
.transition().duration(6000)
.attr("transform", "translate(0," + 0 + ")")
The other answer is okay but this doesn't animate the graph.
Here is how I would do it.
I would add an animation tween to the path so it tweens from 0 to the point on the path.
Something like so :
//create an array of 0's the same size as your current array :
var startData = areaData.map(function(datum) {
return 0;
});
//use this and tween between startData and data
var path = vis.append("path")
.datum(startdata1)
.attr("fill", 'lightgrey')
.attr("d", area)
.transition()
.duration(1500)
.attrTween('d', function() {
var interpolator = d3.interpolateArray(startData, areaData );
return function(t) {
return area(interpolator(t));
}
});
The reason why yours wasn't working was because of this line :
.x(function(d) {
return xRange(areaData.indexOf(d));
})
d at this point is a value between 0 and the current piece of data, so areaData.indexOf(d) will not work.
Just change this :
.x(function(d,i) {
return xRange(i);
})
This will increment along the x axis :)
Updated fiddle : https://jsfiddle.net/thatOneGuy/o7df3tyn/17/
The data is in an array of objects where the
Data = [object{name:"FIRST TECH", value:2477}];
The technology names change and I am trying to place them to the left of the bar they are associated with.
I'm not sure if I'm doing this in the best practice, but when I get the text appended to the side it is invisible. I've tried changing the class name, changing the color, z-index, position:absolute, it always remains hidden.
What do I need to do in order to get the label correctly on the side?
Code:
<style>
h2{
text-align:center;
margin-left: auto;
margin-right: auto;
}
.abcxyz{
fill:black;
color:#000;
text-anchor: end;
}
.chart {
width:800px;
display:block;
margin:auto;
background-color:#c7d9e8;
}
.chart rect {
fill: steelblue;
}
.chart rect:hover{
fill:brown;
}
.values {
fill: white;
font: 12px sans-serif;
text-anchor: end;
}
</style>
<script>
$(document).ready(function(){
var return_data;
$.ajax({
url: '<?php echo site_url('metrics/getTechDocs') ?>',
type: 'GET',
success: function(data){
data = JSON.parse(data);
set_return_data(data);
drawGraph(data);
},
error: function(data){
console.log("error");
}
});
});
function set_return_data(data){
return_data = data;
console.log (return_data);
}
function formatGraphData(data){
var newData = new Array();
for(x in data){
tmp = {name: x , value: data[x].length};
newData.push(tmp);
}
newData.sort(function(a,b){return b.value - a.value} );
return newData;
}
function drawGraph(rawData){
rawData = formatGraphData(rawData);
var width = 800,
barHeight = 30;
var x = d3.scale.linear()
.domain([0, rawData[0].value])
.range([10, width]);
var y = d3.scale.linear()
.domain(rawData.map(function(d){return d.name}))
.range([0, barHeight * rawData.length]);
var chart = d3.select(".chart")
.attr("height", barHeight * rawData.length);
var bar = chart.selectAll("g")
.data(rawData)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("text")
.attr("class", "abcxyz")
.attr("y", barHeight / 2 )
.text(function(d){return d.name});
bar.append("rect")
.attr("height", barHeight - 1)
.attr("width", function(d){return x(d.value);});
bar.append("text")
.attr("class", "values")
.attr("x", function(d) { return x(d.value) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d){return d.value;});
}
</script>
<div>
<h2>Frequency of Technology Terms</h2>
<svg class="chart"></svg>
</div>
SVG doesn't know z-order or anything similar. The elements are displayed in the order they are added in. So to make the text appear on top of the bars, draw the bars first and then the text.