Reputation: 1038
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?
Upvotes: 1
Views: 2378
Reputation: 108512
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>
Upvotes: 1