I have a map of Europe divided by countries and different measures to be represented using a choropletic map.
Based on the selected radio button, the map is colored according to the values in the csv file.
Here is the code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="./map.css" media="screen" />
</head>
<body>
<div id="map-container"></div>
<div id="radio-container">
<form id="radio-selector">
<input type="radio" name="radio-selector" id="rb1" value="m1" checked />
<label for="rb1">Measure 1</label>
<br>
<input type="radio" name="radio-selector" id="rb1" value="m2" />
<label for="rb2">Measure 2</label>
<br>
<input type="radio" name="radio-selector" id="rb1" value="m3" />
<label for="rb3">Measure 3</label>
</form>
</div>
<script src="./map.js"></script>
</body>
</html>
map.js
var csvValue = [];
var projection = d3.geoMercator()
.scale(500)
.translate([200, 700])
var path = d3.geoPath().projection(projection);
var width = 700;
var height = 400;
var svg = d3.select("#map-container").append("svg")
.attr("id", "container-map-svg")
.attr("width", width)
.attr("height", height);
// to color countries
var colors = d3.scaleLinear()
.domain([0, 100])
.range(["#131313", "#ba3c28"]);
var measSelected = document.querySelector('input[name=radio-selector]:checked').value;
var pathToNuts0 = 'https://gist.githubusercontent.com/rveciana/5919944/raw/2fef6be25d39ebeb3bead3933b2c9380497ddff4/nuts0.json';
d3.queue()
.defer(d3.json, pathToNuts0)
.defer(d3.csv, './data.csv')
.await(makeMap);
function makeMap(error, nuts0, data) {
if (error) {
console.log("*** ERROR LOADING FILES: " + error + " ***");
throw error;
}
csvValue = d3.nest()
.key(function(d) {
return d.MEASURE;
})
.object(data);
var country = topojson.feature(nuts0, nuts0.objects.nuts0);
// create map
svg.selectAll("path")
.data(country.features)
.enter().append("path")
.attr("class", "country")
.attr("id", function(d) {
return "country" + d.properties.nuts_id;
})
.attr("d", path);
colorCountries();
}
function colorCountries() {
svg.selectAll("path")
.attr("fill", function(d) {
var col = +getColor(d.properties.nuts_id);
return colors(col);
});
}
var getColor = function(nutsId) {
measSelected = document.querySelector('input[name=radio-selector]:checked').value;
var complete = csvValue[measSelected].slice();
var selectedValue = complete.find(function(tupla) {
return tupla.ID_NUT == nutsId;
});
if (selectedValue == null) {
return -1;
}
else {
var value = selectedValue.VALUE;
return value;
}
}
function measures() {
var measSelected = document.querySelector('input[name="radio-selector"]:checked').value;
}
var updateRadio = function() {
measSelected = $('input[name=radio-selector]:checked', '#desses').val();
colorCountries();
measures();
}
$("#radio-selector").on("change", updateRadio);
data.csv
ID_NUT,MEASURE,VALUE
AT,m1,97.1
AT,m2,74
AT,m3,28.53
BE,m1,98
BE,m2,97.1
BE,m3,8
BG,m1,94.5
BG,m2,56
BG,m3,38.42
CY,m1,99.32
CY,m2,91
CY,m3,23.42
CZ,m1,98.5
CZ,m2,4
CZ,m3,64.51
DE,m1,97
DE,m2,2
DE,m3,78.77
DK,m1,96.8
DK,m2,95
DK,m3,86.95
EE,m1,95.8
EE,m2,79
EE,m3,84.10
EL,m1,96.4
EL,m2,68
EL,m3,42.78
ES,m1,93.9
ES,m2,69
ES,m3,95.4
FI,m1,97.8
FI,m2,36
FI,m3,98.65
FR,m1,97.9
FR,m2,74
FR,m3,99.75
HR,m1,99.1
HR,m2,39
HR,m3,63.78
HU,m1,96.12
HU,m2,84
HU,m3,81
IE,m1,98.55
IE,m2,89
IE,m3,69.4
IT,m1,99.65
IT,m2,40
IT,m3,75.93
LT,m1,97.45
LT,m2,56
LT,m3,93.67
LU,m1,97.63
LU,m2,19
LU,m3,31.48
LV,m1,95.24
LV,m2,71
LV,m3,39
MT,m1,96.52
MT,m2,85
MT,m3,93
NL,m1,98
NL,m2,39
NL,m3,88.88
PL,m1,99.10
PL,m2,77
PL,m3,15
PT,m1,94.15
PT,m2,95
PT,m3,15
RO,m1,97
RO,m2,71
RO,m3,74
SE,m1,89.4
SE,m2,92
SE,m3,69.64
SI,m1,97.86
SI,m2,52
SI,m3,74.78
SK,m1,98
SK,m2,85
SK,m3,88
UK,m1,99.4
UK,m2,100
UK,m3,97
The code is correct, it works and doesn't generate errors.
The problem I would like to solve is the color question.
In csv file, all values are in the range [0, 100] because they represent percentages.
As seen in the csv, the values corresponding to m1 are very high values (>=90) while those referring to m2 and m3 vary a lot.
If I use only one color scale (as written in the code) whose domain is [0, 100], the coropletic map ridden to m1 is not very significant.
How can I solve this problem?
What I would like to do is use a single color scale for all three measurements but make sure that the differences, even the smallest, between the values are visible.
My question is more theory than practice. I don't care about the code, if there is better.
I would really like an idea-level solution, how can I deal with and solve this problem?
Thanks
Question off-topic: how do I use a snippet stack in this case? How can I add an external file (data.csv)?
----------
I modified my code like this:
var colors = d3.scaleQuantile()
.domain([0, 100])
.range(["#131313", "#241715", "#341b17", "#451f19", "#56231b", "#67281e", "#772c20", "#883022", "#993424", "#a93826", "#ba3c28"]);
Unfortunately I didn't get any visual result (or even errors).
With both scaleLinear() and scaleQuantile() the result is this:
Other question. Using this technique (which if I understand correctly fits according to the data domain) would I have different legends for each measure?
My data are in this form:
ID,COUNTRY,YEAR,A,B,C
AL,Albania,2000,98,50,10
AL,Albania,2001,41,2,14
AL,Albania,2002,75,51,10
DE,Germany,2000,74,21,25
DE,Germany,2001,46,2,48
DE,Germany,2002,74,81,90
...
So I don't have a simple array like var data = [..., ...].
There are several solutions for your problem. However, the "correct" solution in this case is using the adequate scale.
Before talking about that adequate scale, let's look at your problem closely and discuss some continuous scale approaches.
Your problem
As you explained in the question, the problem is that your data is heavily skewed towards one end of the domain.
To visualize it, I created this simple dataset...
var data = [2, 30, 60, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99];
... going from 0 to 100, but "skewed to the right".
Given your colours, this is the result of the use of a simple linear scale:
var data = [0, 30, 60, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100];
var scale = d3.scaleLinear()
.domain([0, 100])
.range(["#131313", "#ba3c28"])
var div = d3.select("body").selectAll(null)
.data(data)
.enter()
.append("div")
.style("background-color", d => scale(d))
div {
width: 20px;
height: 20px;
display: inline-block;
margin: 4px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
As you know, we cannot easily see the differences for most of the values.
You could try to make your domain skewed as well. For instance, using a power scale with a high exponent:
var data = [0, 30, 60, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100];
var scale = d3.scalePow()
.exponent(10)
.domain([0, 100])
.range(["#131313", "#ba3c28"])
var div = d3.select("body").selectAll(null)
.data(data)
.enter()
.append("div")
.style("background-color", d => scale(d))
div {
width: 20px;
height: 20px;
display: inline-block;
margin: 4px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
The problem of this approach is that it will be a game of trial and error, until you get the right exponent, which will be different for each data set...
So, let's drop the continuous scale and use the "correct" scale:
The quantile scale
Instead of a continuous scale, the best scale to see the differences in your population is a quantile scale. According to the API:
Quantile scales map a sampled input domain to a discrete range. The domain is considered continuous and thus the scale will accept any reasonable input value; however, the domain is specified as a discrete set of sample values. The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. To compute the quantiles, the domain is sorted, and treated as a population of discrete values. (emphasis mine)
So, the first step is creating the range array. Let's create an array of 10 colours. Based on your colours, it will be:
["#131313", "#241715", "#341b17", "#451f19", "#56231b", "#67281e", "#772c20", "#883022", "#993424", "#a93826", "#ba3c28"]
Then, using that range, we create our quantile scale:
var scale = d3.scaleQuantile()
.domain(data)
.range(["#131313", "#241715", "#341b17", "#451f19", "#56231b", "#67281e", "#772c20", "#883022", "#993424", "#a93826", "#ba3c28"])
This is the demo:
var data = [0, 30, 60, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 100];
var scale = d3.scaleQuantile()
.domain(data)
.range(["#131313", "#241715", "#341b17", "#451f19", "#56231b", "#67281e", "#772c20", "#883022", "#993424", "#a93826", "#ba3c28"])
var div = d3.select("body").selectAll(null)
.data(data)
.enter()
.append("div")
.style("background-color", d => scale(d));
div {
width: 20px;
height: 20px;
display: inline-block;
margin: 4px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
Related
TLDR: I have an NVD3 graph that shows tick lines all across the axis, but I would like to change it so it only displays on the axis lines if possible.
Here is a live example:
var app = angular.module('plunker', ['nvd3']);
app.controller('MainCtrl', function($scope) {
$scope.options = {
chart: {
type: 'lineChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 80,
left: 55
},
x: function(d){ return d.x; },
y: function(d){ return d.y; },
useInteractiveGuideline: true,
xAxis: {
axisLabel: 'Timeline',
tickFormat: function(d) {
return d3.time.format('%B %d')(new Date(d))
},
ticks: 6,
showMaxMin: false
},
yAxis: {
axisLabel: 'Molecular density (kg/m^3)',
tickFormat: function(d){
return d3.format('.02f')(d);
},
axisLabelDistance: -10,
showMaxMin: false
}
}
};
$scope.data = [{"key":"K7 molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":9},{"x":1435881600000,"y":8},{"x":1435968000000,"y":8},{"x":1436054400000,"y":9},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":8},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":7},{"x":1436659200000,"y":8}],"area":true,"color":"#0CB3EE"},{"key":"N41 type C molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":7},{"x":1435881600000,"y":8},{"x":1435968000000,"y":9},{"x":1436054400000,"y":7},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":9},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":9},{"x":1436659200000,"y":8}],"area":true,"color":"#383838"}];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>Angular-nvD3 Line Chart</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.css"/>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.js"></script>
<script src="https://rawgit.com/krispo/angular-nvd3/v1.0.1/dist/angular-nvd3.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<nvd3 options="options" data="data" class="with-3d-shadow with-transitions"></nvd3>
</body>
</html>
Is there any way I could make the tick lines appear just on the axes line only? To make it clear, this is what it looks like:
I used a different library to generate the following plot, and I would like the tick lines to appear just on the axis lines like this example instead:
It appears that there is no real way to do this with NVD3 as it does not provide a way to show tick marks on the axis. However, we could add our own tick marks by fetching the chart SVG and then modifying it.
I've attached an example that adds tick marks to X-Axis, and it is basically slightly modified based on this jsfiddle here: http://jsfiddle.net/3r88bgjw
var data;
data = [{
values: [],
}, ];
var i, x;
var prevVal = 3000;
var tickCount = 2000;
for (i = 0; i < tickCount; i++) {
x = 1425096000 + i * 10 * 60; // data points every ten minutes
if (Math.random() < 0.8) { // add some gaps
prevVal += (Math.random() - 0.5) * 500;
if (prevVal <= 0) {
prevVal = Math.random() * 100;
}
data[0].values.push({
x: x * 1000,
y: prevVal
});
}
}
var chart;
nv.addGraph(function() {
chart = nv.models.historicalBarChart();
chart.xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis
.color(['#68c'])
.useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing
.margin({
"left": 80,
"right": 50,
"top": 20,
"bottom": 30,
})
.noData("There is no data to display.")
.duration(0);
var tickMultiFormat = d3.time.format.multi([
["%-I:%M%p", function(d) {
return d.getMinutes();
}], // not the beginning of the hour
["%-I%p", function(d) {
return d.getHours();
}], // not midnight
["%b %-d", function(d) {
return d.getDate() != 1;
}], // not the first of the month
["%b %-d", function(d) {
return d.getMonth();
}], // not Jan 1st
["%Y", function() {
return true;
}]
]);
chart.xAxis
.showMaxMin(false)
.tickPadding(10)
.tickFormat(function(d) {
return tickMultiFormat(new Date(d));
});
chart.yAxis
.tickFormat(d3.format(",.0f"));
var svgElem = d3.select('#chart svg');
svgElem
.datum(data)
.transition()
.call(chart);
// make our own x-axis tick marks because NVD3 doesn't provide any
var tickY2 = chart.yAxis.scale().range()[1];
var lineElems = svgElem
.select('.nv-x.nv-axis.nvd3-svg')
.select('.nvd3.nv-wrap.nv-axis')
.select('g')
.selectAll('.tick')
.data(chart.xScale().ticks())
.append('line')
.attr('class', 'x-axis-tick-mark')
.attr('x2', 0)
.attr('y1', tickY2 + 7)
.attr('y2', tickY2)
.attr('stroke-width', 3);
// set up the tooltip to display full dates
var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p');
var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator();
var tooltip = chart.interactiveLayer.tooltip;
tooltip.contentGenerator(function(d) {
d.value = d.series[0].data.x;
return contentGenerator(d);
});
tooltip.headerFormatter(function(d) {
return tsFormat(new Date(d));
});
return chart;
});
<div>Try resizing the panel to see the various types of time labels.</div>
<br>
<div id="chart">
<svg></svg>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.js"></script>
The first time I load data, the graph draws correctly, but when I load a different data set, the graph remains unchanged.
I switch between datasets using buttons. The first click always draws the graph correctly, no matter what button I click. But I can't update the graph after it is drawn by clicking on the other button. Any help is very much appreciated,thank you!
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 900;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale
.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
});
bar
.append("rect")
.attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
CodePen: https://codepen.io/rfripp2/pen/porpaLL
This is the expected behavior. Let's look at your code:
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
The select all statement selects all existing elements matching the selector that are children of elements in the selection chart.
The data method binds a new data array to this selection.
The enter method returns a new selection, containing a placeholder for every item in the data array which does not have a corresponding element in the selection.
The append method returns a newly appended child element for every element in the selection it is called on.
Running the code
The first time you call the draw function you have no g elements, so the selection is empty. You bind data to this empty selection. You then use the enter selection. Because there are two data items and no elements in the selection, enter contains two placeholders/elements. You then use append to add those elements.
The second time you call the draw function you have two g elements, so the selection has two elements in it. You bind data to this selection. You then use the enter selection. Because you already have two elements and you only have two data points, the enter selection is empty. As a consequence, append does not create any new elements.
You can see this by using selection.size():
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 900;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale
.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
});
console.log("The enter selection contains: " + bar.size() + "elements")
bar
.append("rect")
.attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
Solution
We want to use both the update and the enter selection (if the dataset ever changes in size, we'd likely want the exit selection too). We can use .join() to simplify this, join removes elements in the exit selection (surplus elements which don't have a corresponding data item), and returns the merged enter selection (new elements for surplus data items) and update selection (preexisting elements).
The nesting of your elements into a parent g and child rect is unnecessary here - and requires additional modifications. By positioning the bars directly we avoid the need for the parent g:
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scaleBand().range([0, width], 0.9);
let y = d3.scaleLinear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("rect")
.data(dataSet)
.join("rect")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
This requires updating your version of D3 from v3 (you are actually using two versions of D3, v3 and v4, both fairly outdated, and both with different method names, actually with different ways of handling the enter selection).
If you wish to use d3v4, then the join method is not available, but we can merge enter and update:
When I say update selection, I'm refering to the initial selection:
// update selection:
let bar = chart
.selectAll("rect")
.data(dataSet);
// enter selection:
bar.enter().append("rect")
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scaleBand().range([0, width], 0.9);
let y = d3.scaleLinear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("rect")
.data(dataSet);
bar.enter().append("rect")
.merge(bar)
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.0/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
And lastly, if you wish to keep d3v3 (we are on v7 already), we can rely on an implicit merging of update and enter on enter (modifying the update selection). This "magic" was removed in v4, partly because it was not explicit. To do so we need to break your method chaining so that bar contains the
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
// update selection:
let bar = chart
.selectAll("rect")
.data(dataSet);
// enter selection:
bar.enter().append("rect")
bar.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
Note: d3v4 made changes to method names that break code from v3. This required changes to d3.scale.linear / d3.scale.ordinal in the snippets using v4 and 7 (using merge and join respectively).
I've implementing barchart to denote my result set. I am trying to create this design using c3js. I referred the documentation but have not getting the shaded design. Please someone guide me to solve this.
My Code Snippet is,
var chart = c3.generate({
bindto: '#chart',
size : {
width: 600,
height: 200
},
data: {
columns: [
["data1", 40, 20, 20, 20],
["data2", 20, 10, 30, 30]
],
type: 'bar',
groups: [
['data1', 'data2']
],
order: null,
labels: {
format: function(v, id, i, j) {
return v;
}
}
},
bar: {
space: 0.2,
width: {
ratio: 0.2 // this makes bar width 50% of length between ticks
}
},
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.3.0/c3.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.3.0/c3.min.js"></script>
<div id="chart"></div>
My requirement is to design like below image in bars in barchart,
Thanks
The solution in the snippet introduces some d3 SVG manipulation which puts a region over the bars of each targeted series. The region has a hatched grey line and a semi-transparent fill. The function to do this is written to be portable i.e. outside of the C3 construtor params, and is invoked by the onrendered c3 event.
The doClone() function duplicates nodes in place which is useful to know, and the creation of the pattern and use as a colour via 'url(#patternid)' is also a potentially useful technique.
Also available at https://codepen.io/JEE42/pen/yRWbvq
function doClone(node){ // clone the given node
return d3.select(node.parentNode.insertBefore(node.cloneNode(true), node.nextSibling));
}
function hatchBars(hatchTargets){ // Place a hatching pattern over the target bars.
for (var i = 0; i < hatchTargets.length; i = i + 1){
d3.select('.c3-bars-' + hatchTargets[i]).each(function(d, i){
d3.select(this).selectAll('path').each(function(d, i){
var node = d3.select(this).node();
var daClone = doClone(node);
daClone
.style('fill', 'url(#hash4_4)')
.style('stroke', 'url(#hash4_4)');
});
})
}
}
c3.chart.internal.fn.afterInit = function () {
d3.select('defs')
.append('pattern')
.attr('id', "hash4_4") // use id to get handle in a moment
.attr('width', 14)
.attr('height', 14)
.attr('patternUnits', "userSpaceOnUse")
.attr('patternTransform', "rotate(45 0 0 )")
.append("rect")
.attr('width', 14)
.attr('height', 14)
.attr('fill', '#00000000') // transparent background
d3.select('#hash4_4') // get the pattenn
.append('line') // add a line
.attr('y2', 14)
.style('stroke', "#00000044") // semi-transparent bars
.attr('stroke-width', 14)
};
//
// Standard C3 chart render with one twist which is the onrendered event call at the end.
//
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
['data1', -30, 200, 200, 400, -150, 250],
['data2', 130, 100, -100, 200, -150, 50],
],
type: 'bar',
groups: [
['data1', 'data2']
]
},
grid: {
y: {
lines: [{value:0}]
}
},
onrendered: function () { // execute after drawn
hatchBars(['data2']); // Place a hatching pattern over the target bars.
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.7/c3.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.7/c3.min.js"></script>
<div class='chart-wrapper'>
<div class='chat' id="chart"></div>
</div>
I´m noob using d3js I´m trying add a new vertical on Basic Horizontal Bar Chart of d3js. To test I´m using codepen but the vertical line is not shown.
HTML file
<head>
<!-- Plotly.js -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv" style="width: 480px; height: 400px;"><!-- Plotly chart will be drawn inside this DIV --></div>
<script>
<!-- JAVASCRIPT CODE GOES HERE -->
</script>
</body>
JS file
var trace1 = {
x: [20],
y: ['giraffes'],
name: 'SF Zoo',
orientation: 'h',
marker: {
color: 'rgba(55,128,191,0.6)',
width: 1
},
type: 'bar'
};
var data = [trace1];
var layout = {
title: 'Colored Bar Chart',
barmode: 'stack'
};
Plotly.newPlot('myDiv', data, layout);
var y = d3.scale.linear().range([0, 400]);
var svg = d3.select(document.getElementById('myDiv'));
svg.append("line")
.attr("x1", 10)
.attr("y1", y(0))
.attr("x2", 10)
.attr("y2", y(1))
.style("stroke", "black");
Your svg variable is a HTML <div> element:
<div id="myDiv"></div>
//"myDiv" is the ID of the div
var svg = d3.select(document.getElementById('myDiv'));
//you're getting the div here -----------------^
However, you cannot append a SVG line to a HTML div.
Solution: select the svg itself:
var svg = d3.select("svg");
Now your svg variable points to the SVG, in which you can append a SVG line.
Here is your code with that change:
var trace1 = {
x: [20],
y: ['giraffes'],
name: 'SF Zoo',
orientation: 'h',
marker: {
color: 'rgba(55,128,191,0.6)',
width: 1
},
type: 'bar'
};
var data = [trace1];
var layout = {
title: 'Colored Bar Chart',
barmode: 'stack'
};
Plotly.newPlot('myDiv', data, layout);
var y = d3.scale.linear().range([0, 400]);
var svg = d3.select("svg");
svg.append("line")
.attr("x1", 10)
.attr("y1", y(0))
.attr("x2", 10)
.attr("y2", y(1))
.style("stroke", "black");
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>
<div id="myDiv" style="width: 480px; height: 400px;"><!-- Plotly chart will be drawn inside this DIV --></div>
PS: You don't need getElementById in a D3 code. To select that div, for instance, just do d3.select("#myDiv").
I'm trying to place an svg element on a c3 chart such that it aligns horizontally with one of the tick marks.
See fiddle here: https://jsfiddle.net/4sw82k1z/3/
For example, I'd like the red label to be centered above tick mark '1' and the green label centered above tick mark '3'.
I'm new to the d3 world. The way that I've tried to accomplish this is in absolute coordinates, which fail when the 'html' pane of the fiddle is resized. To see what I mean, click drag the size of the 'html' window.
var rightlabel = d3.select("#chart svg")
.append("svg").attr("width", 1200).attr("height", 50) //container for txt
.append("text").text("i'm a label in the green region") //text element
.style("fill", "green").attr("transform","translate(400,20)");
What's the proper way to achieve this?
Hook the redrawed event and reposition the labels. You can also set position properly based on some of the internals of c3:
var chart = c3.generate({
data: {
columns: [
['data1', 100, 250, 100, 300, 75],
['data2', 60, 500, 250, 450, 300],
]
},
onresized: function () {
setTimeout(updateLabels, 200);
}
});
var rightlabel = d3.select("#chart svg g")
.append("text")
.text("i'm a label in the green region").style("fill", "green")
.attr("transform","translate(" + (chart.internal.x(3)) + ",20)")
.style("text-anchor","middle");
var leftlabel = d3.select("#chart svg g")
.append("text")
.text("i'm a label in the red region").style("fill", "red")
.attr("transform","translate(" + (chart.internal.x(1)) + ",20)")
.style("text-anchor","middle");
function updateLabels(){
rightlabel.attr("transform","translate(" + chart.internal.x(3) + ",20)");
leftlabel.attr("transform","translate(" + chart.internal.x(1) + ",20)");
}
chart.regions.add([{axis: 'x', end: 2, class: 'c3-region-r'},{axis: 'x', start: 2, class: 'c3-region-gr'}]);
.c3-region-gr{
fill: green;
fill-opacity: 0.1;
}
.c3-region-r{
fill: red;
fill-opacity: 0.1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet"/>
<script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script>
<div id="chart"></div>