Reputation: 28868
I am trying to control the color of a text inside a graph rendered by d3
:
Here is what I tried so far, in the bottom of my js code that creates the graph:
d3.select('#gender_divide svg')
.datum(datum)
.transition().duration(500)
.attr('width', 400)
.attr('height', 400)
.attr("fill","white")
.attr('stroke', 'white')
.call(chart);
This results in a white stroke around the text, but the text itself stays black, as you can see:
Do you know how to change the text style inside the graph?
<div id="gender_divide"><svg style="width:350px;height:350px; body { color: white;}"> </svg></div>
<script>
data_gender_divide=[{"values": [{"value": 6.473124955585393, "label": "unknown"}, {"value": 71.34687526882524, "label": "men"}, {"value": 22.17999977558936, "label": "women"}], "key": "Serie 1"}];
nv.addGraph(function() {
var chart = nv.models.pieChart();
chart.margin({top: 30, right: 60, bottom: 20, left: 60});
var datum = data_gender_divide[0].values;
chart.tooltipContent(function(key, y, e, graph) {
var x = String(key);
var y = String(y) + ' %';
tooltip_str = '<center><b>'+x+'</b></center>' + y;
return tooltip_str;
});
chart.showLegend(false);
chart.showLabels(true);
chart.donut(false);
chart
.x(function(d) { return d.label })
.y(function(d) { return d.value });
chart.width(350);
chart.height(350);
d3.select('#gender_divide svg')
.datum(datum)
.transition().duration(500)
.attr('width', 400)
.attr('height', 400)
.call(chart);
});
</script>
Here is a working jsfiddle : http://jsfiddle.net/oz123/QyrwC/8/
Upvotes: 2
Views: 11732
Reputation: 22882
There are two issues with your code. The first is relatively simple, the second is more subtle.
In order to control the color of the text, you need to explicitly use d3
to select the <text>
elements you want to change. You need to do something like this:
d3.selectAll("#gender_divide text").attr("fill", "white");
You're on the right track in that your code tries to set the .attr("fill", "white")
, which is a valid way to change the fill color of a <text>
element. However, NVD3 is automatically setting the style="fill: rgb(0, 0, 0)"
for your <text>
elements, which is overwriting the fill
you set. So, instead of setting .attr("fill", "white")
, set the fill property of the style like this:
d3.selectAll("#gender_divide text").style("fill", "white");
Then NVD3 will not overwrite your fill, and your <text>
will show up as white.
Working JSFiddle here.
Upvotes: 7
Reputation: 1890
Try this code:
Fiddle here
D3.Js
d3.selectAll("text").style("fill","red");
Upvotes: 1
Reputation: 71160
Try adding the below to your JS:
d3.select('#gender_divide text').attr("fill","white")
The text within text
elements can be colored using fill instead of stroke (which provides an outline). In your code, you arent implicitly selecting the text
elements, merely the parent SVG.
An alternative would be to add the below to your CSS:
#gender_divide text{
fill:white;
}
Upvotes: 0