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>
I want to make a bar chart with two sets of stacked bars which are grouped together to compare the two groups of stacked bars. This should be displayed in the following manner:
I have gone through this link
But it didn't help me plot something like you see in the above image. I even tried sending two data sets like [[s1, s2, s3], [s4, s5, s6]] But it didn't help me plot the chart.
Does anyone know how to do it?
Any help will be greatly appreciated.
Thanks in advance.
Setting the option stackSeries: true will create the desired display for bar charts.
Official sources:
jqPlot Source code: source code, version 1.0.8r1250 of
2013-03-27. For this issue, src/jqplot.core.js lines 2499, 2563, and 2649.
jqPlot Documentation: It says that the API Documentation is most accurate. you can also see the webpage, README.txt,
optionsTutorial.txt, jqPlotOptions.txt, jqPlotOptions.txt,
jqPlotCssStyling.txt, usage.txt, changes.txt in the 1.0.8r1250
general release
The jqPlot documentation is not up to date so I took a look at the source code. Unfortunately, there is no way to directly have two sets of bars with a stacked-bar chart. The jqPlot.stackSeries property is only a boolean value. It's only function is to tell jqPlot to stack each series on top of each other for as many bars as there are values in the different series. Each series is plotted one value per bar with the first series being on the bottom. In other words, all [0] values are plotted in the first bar, [1] values in the second, etc. The amount shown within the bar is the sum of the [n] value for the current series and all prior series. There is no way to specify that there are two, or more, groupings of series. The capability to do what is desired just does not exist in jqPlot.
But you can accomplish what you desire:
The fact that jqPlot does not natively support what you want does not mean that you can not do it, merely that you need to get creative.
The graph you desire can be looked at as being two separate graphs that have been overlaid upon each other with spacing between the bars on the individual graphs permitting enough space (seriesDefaults.rendererOptions.barMargin) for the bars from the other graph to be overlaid next to them.
You can use jqPlot to create:
That graph has the scale, background and grid-lines you desire set to be visible. Note that the graph has an extra bar in it. This is needed to provide enough background and grid-lines for the last bar provided by the other graph.
You can also use jqPlot to create the second graph:
This graph has the scale and grid-lines set in jqPlot to not be visible.
seriesDefaults.axes.xaxis.tickOptions.show = false;
seriesDefaults.axes.yaxis.tickOptions.show = false;
etc.
The background is set to be transparent. Note that you are going to need to offset the position of this graph somewhat to the right when positioning the <div> relative to the first graph.
Overlaid, you end up with:
You then use a blank <div> with the same background color as the background color of your webpage and overlay that to cover the extra bar on the first graph, but leaving enough of the first graph's background and grid-lines to extend a bit past the last bar of the second graph.
You will end up with:
You can see a working solution at at JSFiddle using jqPlot 1.0.8r1250.
Comparing the original request vs. the final version of the graph produced using this method you can see that they are very close:
Between the two the most noticeable difference is the larger space between the Y-axis in the jqPlot version. Unfortunately, there does not appear to be an option to reduce that amount for stacked bar charts.
Note that the lack of a border on the right of the graph this code produces is intentional because it did not exist in the original request. Personally, I prefer having a border on the right side of the graph. If you change the CSS a bit, that is easy to obtain:
My preferred version of the graph includes a border on the left and balances the whitespace:
You can see a working JSFiddle of this version.
All-in-all it is not that difficult. It would, of course, be easier if jqPlot supported multiple sets of bars. Hopefully it will at some point. However, the last release was 2013-03-27 and there does not appear to have been any development work after that time. Prior to that there were releases every few months. But, jqPlot is released under the GPL and MIT licenses so anyone could continue the work.
$(document).ready(function () {
//Numbers derived from desired image
//var s1 = [10, 29, 35, 48, 0];
//var s2 = [34, 24, 15, 20, 0];
//var s3 = [18, 19, 26, 52, 0];
//Scale to get 30 max on plot
var s1 = [2, 5.8, 7, 9.6, 0];
var s2 = [6.8, 4.8, 3, 4, 0];
var s3 = [13.6, 8.8, 3, 7.8, 0];
plot4 = $.jqplot('chart4', [s1, s2, s3], {
// Tell the plot to stack the bars.
stackSeries: true,
captureRightClick: true,
seriesColors: ["#1B95D9", "#A5BC4E", "#E48701"],
seriesDefaults: {
shadow: false,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
// jqPlot does not actually obey these except barWidth.
barPadding: 0,
barMargin: 66,
barWidth: 38,
// Highlight bars when mouse button pressed.
// Disables default highlighting on mouse over.
highlightMouseDown: false
},
title: {
text: '', // title for the plot,
show: false,
},
markerOptions: {
show: false, // wether to show data point markers.
},
pointLabels: {
show: false
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
tickOptions: {
show: false
},
lastPropertyConvenience: 0
},
yaxis: {
// Don't pad out the bottom of the data range. By default,
// axes scaled as if data extended 10% above and below the
// actual range to prevent data points right on grid boundaries.
// Don't want to do that here.
padMin: 0
}
},
legend: {
show: false,
location: 'e',
placement: 'outside'
},
grid: {
drawGridLines: true, // wether to draw lines across the grid or not.
shadow: false, // no shadow
borderWidth: 1,
background: 'white', // CSS color spec for background color of grid.
lastPropertyConvenience: 0
},
lastPropertyConvenience: 0
});
});
$(document).ready(function () {
//Numbers derived from desired image
//var s1 = [10, 29, 35, 48, 0];
//var s2 = [34, 24, 15, 20, 0];
//var s3 = [18, 19, 26, 52, 0];
//Scale to get 30 max on plot
var s1 = [2, 5.8, 7, 9.6, 0];
var s2 = [6.8, 4.8, 3, 4, 0];
var s3 = [3.6, 3.8, 5.2, 10.4, 0];
plot4 = $.jqplot('chart5', [s1, s2, s3], {
// Tell the plot to stack the bars.
stackSeries: true,
captureRightClick: true,
seriesColors: ["#754DE9", "#666666", "#000000"],
seriesDefaults: {
shadow: false,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
// jqPlot does not obey these options except barWidth.
show: true,
barPadding: 0,
barMargin: 66,
barWidth: 38,
// Highlight bars when mouse button pressed.
// Disables default highlighting on mouse over.
highlightMouseDown: false
},
title: {
text: '', // title for the plot,
show: false,
},
markerOptions: {
show: false, // wether to show data point markers.
},
pointLabels: {
show: false
}
},
axesDefaults: {
//show: false
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
tickOptions: {
show: false
},
lastPropertyConvenience: 0
},
yaxis: {
show: false,
// Don't pad out the bottom of the data range. By default,
// axes scaled as if data extended 10% above and below the
// actual range to prevent data points right on grid boundaries.
// Don't want to do that here.
padMin: 0,
tickOptions: {
show: false
},
}
},
legend: {
show: false,
location: 'e',
placement: 'outside'
},
grid: {
drawGridLines: false, // wether to draw lines across the grid or not.
shadow: false, // no shadow
borderWidth: 10,
background: 'transparent', // CSS color for background color of grid.
gridLineColor: 'transparent', // *Color of the grid lines.
borderColor: 'transparent', // CSS color for border around grid.
lastPropertyConvenience: 0
},
lastPropertyConvenience: 0
});
});
#cover1 {
padding:0;
margin: 0;
background-color: white;
left: 451px;
width: 88px;
/* Uncomment the next three lines to have a border on the right of the graph and
balanced whitespace:*/
/*
border-left: 2px solid #CCCCCC;
left:476px;
width: 62px;
*/
}
#chart4 .jqplot-xaxis-tick {
visibility: hidden;
}
#chart5 .jqplot-xaxis-tick {
visibility: hidden;
}
#chart4 .jqplot-yaxis-tick {
font: 9px arial
}
<link class="include" rel="stylesheet" type="text/css" href="http://cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.css" />
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="http://cdn.jsdelivr.net/excanvas/r3/excanvas.js"></script><![endif]-->
<script class="include" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Main jqPlot -->
<script class="include" type="text/javascript" src="http://cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.js"></script>
<!-- Additional jqPlot plugins -->
<script class="include" type="text/javascript" src="http://cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.barRenderer.min.js"></script>
<script class="include" type="text/javascript" src="http://cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<div style="position:absolute; left:10px; top:10px;">
<div id="chart4" style="width:548px; height:185px;"></div>
<div id="chart5" style="width:536px; height:185px; top:-185px; left:53px;"></div>
<div id="cover1" style="position: relative; height: 152px; top:-361px;"></div>
</div>
The above code is based on that at the example page listed in the question.
Practical solution...
$(document).ready(function(){
var s1 = [2, 0, 0, 10,11,0, 6, 2, 0,10,11];
var s2 = [7, 0, 0, 4,11,0, 6, 2, 0,10,11];
var s3 = [4, 0, 0, 7,11,0, 6, 2, 0,10,11];
var s4 = [0, 20, 0, 0,0,0, 0, 0, 0,0,0];
plot3 = $.jqplot('chart3', [s1, s2, s3,s4], {
stackSeries: true,
captureRightClick: true,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
rendererOptions: {
barMargin: 30,
highlightMouseDown: true
},
pointLabels: {show: true}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
},
yaxis: {
padMin: 0
}
},
legend: {
show: true,
location: 'e',
placement: 'outside'
}
});
$('#chart3').bind('jqplotDataClick',
function (ev, seriesIndex, pointIndex, data) {
$('#info3').html('series: '+seriesIndex+', point: '+pointIndex+', data: '+data);
}
);
});
Image: