I'm trying to set the width and height of a nvd3 multi bar chart programmatically using
chart.width(600);
chart.height(400);
See the example here:
http://jsfiddle.net/hPgyq/20/
As you can see this really messes up the chart. I know I can do this is CSS with:
#chart svg {
width: 600px;
height: 400px;
}
but I thought this was also possible using the width() and height() functions on the chart. Am I doing something wrong here or am I mis-using the two functions?
Yes it is possible, like you have specified the width & height of the chart, you have to use the d3.select and set its width & height attribute.
Changes to the code are below and there is a version of the code here
function visualizeData(data) {
nv.addGraph(function() {
var width = 600, height = 400;
chart = nv.models.multiBarChart().x(function(d) {
return d.x;
}).y(function(d) {
return d.y;
}).color(['#aec7e8', '#7b94b5', '#486192']).stacked(true)
//.margin({top:150,right:150,bottom:150,left:150})
.width(width).height(height);
chart.multibar.hideable(false);
chart.xAxis.showMaxMin(true).tickFormat(d3.format(',f'));
chart.yAxis.tickFormat(d3.format(',.1f'));
d3.select('#chart svg').datum(data).transition().duration(500).call(chart).style({ 'width': width, 'height': height });
nv.utils.windowResize(chart.update);
return chart;
});
}
For the AngularJs version (angular-nvd3), I had to add the height either in chart options and as an attribute:
chart.html
<nvd3 options='vm.chartOptions' data='vm.chartData' height="250" config="vm.chartConfig">
</nvd3>
chart.controller.js
vm.chartOptions = {
chart : {
height : 250,
type : "pieChart",
donut : true,
showLegend : false,
//The rest of the configuration
};
As it is told in the comments, first seems to control the height of the inner svg and the second does the global chart height.
Related
How can I have the labels outside the bar in a row chart with dc.js?
I'd like a graph like this:
however, the labels are inside the actual bars... is there any settings i need to change to have it like this?
I finally got this working and here is the trick,
As mentioned by the Gordon it can be done on renderlet.
First I have gave the margin for my row chart ,
.margins({ top: 20, right: 20, bottom: 40, left: 110 })
Then took the label outside by giving x value in negative.
.labelOffsetX(-10)
This will perfectly move our label but its still need some style changes to look fine and that need to be done on renderlet,
.on('renderlet', function (chart) {
chart.selectAll("g.row text")
.style("text-anchor", "end")
.call(function (t) {
t.each(function (d) {
var self = d3.select(this);
var text = self.text();
if (text.length > 14) {
self.text('');
text = text.substring(0, 14) + '..';
self.text(text);
}
})
});
})
You can ignore .call() function as I place this just to make sure my label length does not cross certain limit.
Hope that work for you.!
I implemented a composite chart with two bar charts in which one bar chart consists of bars with different colored bars.
Now, I want to create a custom legend that represents each color bar (similar to https://dc-js.github.io/dc.js/examples/pie-external-labels.html used for pie chart).
Below is the code snippet of what I've done so far:
var buttonPress = dc.barChart(composite)
.dimension(joyTimeDimension)
//.renderlet(colorRenderlet)
//.colors('red')
.colors(colorbrewer.Set1[5])
.colorDomain([101, 105])
.colorAccessor(function (d) {
return d.value;
})
.group(btnGroup, "Button Press")
.keyAccessor(function(d) {return d.key[0];})
.valueAccessor(function (d) {
return d.value;
})
.title( function(d){
return [
"Time: "+d.key[0],
"button Name: "+d.key[1],
"button: "+ d.value
].join('\n')
});
var joyStick = dc.barChart(composite)
.dimension(joyTimeDimension)
.colors('blue')
.group(stepperGroup,"Joy Stick Movement")
.keyAccessor(function(d) {return d.key[0];})
.title( function(d){
return [
"Time: "+d.key[0],
"Stepper Position: "+ d.value
].join('\n')
});
composite
.width(1200)
.transitionDuration(500)
.margins({top: 30, right: 50, bottom: 25, left: 40})
.x(d3.time.scale().domain([startDate,currDate]))
.xUnits(function(){return 150;})
//.xUnits(d3.time.second)
.elasticY(true)
.legend(dc.legend().x(1000).y(4).itemHeight(13).gap(5))
.renderHorizontalGridLines(true)
.renderTitle(true)
.shareTitle(false)
.compose([buttonPress, joyStick])
.brushOn(false)
Is there a way to create a custom legend for this scenario?
Thanks in advance.
Let me provide a little bit of background about how the legend is built.
The legend in dc.js is really not all that sophisticated. It just calls .legendables() on the chart, and the chart decides what items to display in the legend.
Each chart has its own special-purpose code for this.
If we look at the source for compositeChart.legendables(), it's just recursively getting the legendables for each child chart and concatenating them:
_chart.legendables = function () {
return _children.reduce(function (items, child) {
if (_shareColors) {
child.colors(_chart.colors());
}
items.push.apply(items, child.legendables());
return items;
}, []);
};
The pie chart creates a legendable for each pie slice:
_chart.legendables = function () {
return _chart.data().map(function (d, i) {
var legendable = {name: d.key, data: d.value, others: d.others, chart: _chart};
legendable.color = _chart.getColor(d, i);
return legendable;
});
};
The legendables for the bar chart come from the stack mixin, which creates a legendable for each stack:
_chart.legendables = function () {
return _stack.map(function (layer, i) {
return {
chart: _chart,
name: layer.name,
hidden: layer.hidden || false,
color: _chart.getColor.call(layer, layer.values, i)
};
});
};
Given that there's currently no way to get a bar chart to display a pie chart's legend, I think the easiest thing to do is override legendables for your bar chart with its custom colors:
buttonPress.legendables = function() {
return btnGroup.all().map(function(kv) {
return {
chart: buttonPress,
// display the value as the text (not sure what you want here)
name: kv.value,
// apply the chart's color scale to get the color
color: buttonPress.colors()(kv.value)
};
})
};
There are probably some more details to be worked out, such as what if the same value occurs twice? I am assuming you can just read the input data from the group and .map() it, but you might need to generate your data a different way.
But this should give the general idea. Lmk if it doesn't work and I'll be glad to follow up.
Using nvd3 multibar chart. When having minimum bars x axis label does not display in center like y axis.
Sample code to generate x axis label.
chart = nv.models.multiBarChart().margin({
top: 30,
right: 28,
bottom: 50,
left: 60
})
.x(function(d) {
return d.x
})
.y(function(d) {
return d.y
})
.color(d3.scale.myColors().range());
chart.xAxis
.showMaxMin(true)
.axisLabel(xAxisLabel)
.tickFormat(xAxisTickFormat)
.tickValues(xaxisValues);
How to solve this problem ?
This might sound strange but try swapping the order of axisLabel and showMaxMin like the following :
chart.xAxis
.axisLabel(xAxisLabel) // axisLabel first
.showMaxMin(true)
.tickFormat(xAxisTickFormat)
.tickValues(xaxisValues);
Hope it helps.
I have used the next workaround. Hope it helps:
var transitions = 0;
d3.select(this.tag + ' svg').transition().each( "start", function() {
transitions++;
}).each( "end", function() {
if( --transitions === 0 ) {
alignaxisCallback();
}
});
function alignaxisCallback(){
var axisWidth = d3.select('.nv-x').node().getBoundingClientRect().width;
d3.select('.nv-x').select('.nv-axislabel').attr('x', axisWidth / 2);
}
Did you try
chart.xAxis.axisLabelDistance(LABEL_OFFSET);
The issue is resolved by updating nvd3 to version 1.8.4 or higher.
I want to add an image in nvd3 piechart legend instead of text.
I have this code but it changes only the text in the tooltip with the image. I want to change and the text in the legend with the same image.
var testdata = [
{
key: "<img src="+"./imgs/facebook.jpg"+">",
y: 1
},
{
key: ""<img src="+"./imgs/twitter.jpg"+">"",
y: 2
} ];
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.key})
.labelThreshold(.08)
.showLabels(true)
.color(d3.scale.category10().range())
.donut(true);
chart.pie.donutLabelsOutside(true).donut(true);
d3.select("#mypiechart")
.datum(testdata)
.transition().duration(1200)
.call(chart);
return chart;});
Any ideas?
This is not currently possible with nvd3.js. The tooltip works because the img element you have specified is being set into a div that isn't contained within the svg element. It doesn't work for the legend or chart labels because those are built using svg text elements. In order to show an image within the chart svg we'd need to use an svg image element.
We could build the svg image elements if we hack the nvd3.js code. Here's an outline of what you could do to get the legend working. You could then decide if you'd want to try something similar in the nv.models.pie code for the chart labels or if you'd just want to set chart.showLabels to false in your chart configuration.
Add a new key in your data to provide the image path:
var testdata = [
{
key: "<img src="+"./imgs/facebook.jpg"+">",
y: 1,
image_path: "./imgs/facebook.jpg"
},
{
key: "<img src="+"./imgs/twitter.jpg"+">",
y: 2,
image_path: "./imgs/twitter.jpg"
} ];
Update the nv.models.legend code to show the image:
seriesEnter.append('circle')
.style('stroke-width', 2)
.attr('class','nv-legend-symbol')
.attr('r', 5);
// Add an svg image into the legend
seriesEnter.append('image')
.attr('xlink:href', function(d) { return d.image_path} )
.attr('height',20)
.attr('width',20)
.attr('y', '-10')
.attr('x', '8');
Update the nv.models.legend code to not show the key:
// Don't add the key value into the legend text
//series.select('text').text(getKey);
Update the nv.models.legend code to consider the image width when determining the legend layout:
//seriesWidths.push(nodeTextLength + 28); // 28 is ~ the width of the circle plus some padding
//Include image width...
seriesWidths.push(nodeTextLength + 48);
I am new to SVG, so sorry if this is a bit of a noob question. I am trying to figure out how to get an image to display with the full width and height of the referenced image. I am using D3.js to build a graph and I want a logo to appear in the corner. The problem is that the image href will be set using javascript, so the image being referenced is never a fixed width or height. What I am wanting is the image to display in it's full width and height, not scaled up or down. What I was hoping for is the ability to automatically set the width and height of the image based on it's content, such as setting the width and height attributes to auto. This however just results in the image not being shown.
d3.select("body")
.append("svg")
.attr('id','mySVG')
.attr({
"width": "100%",
"height": "100%"
})
.attr("viewBox", "0 0 " + width + " " + height )
.attr("preserveAspectRatio", "none");
d3.select('#mySVG')
.append('image')
.attr('image-rendering','optimizeQuality')
.attr('height','auto') <--- This does not work
.attr('width','auto') <--- This does not work
.attr('xlink:href', logoUrl)
.attr('x','0')
.attr('y','0');
How would I go about specifying that the SVG image width and height must be dynamically determined based on the referenced image size?
I don't think 'auto' is a valid value for the 'length' attr of a svg image element. Take a look at the spec here. You might want to use '100%'
You could load the image then inspect the width and height onload.
JSFiddle: http://jsfiddle.net/WQBPC/4/
var logoUrl = 'http://placehold.it/100x50&text=Logo';
//SVG Setup stuff
var svg = d3.select("body").append("svg")
.attr('id','mySVG')
.attr({
"width": '100%',
"height": '100%'
})
var svg_img= svg.append('image')
.attr('image-rendering','optimizeQuality')
.attr('x','0')
.attr('y','0');
//Load image and get size.
var img = new Image();
img.src = logoUrl;
img.onload = function() {
var width = this.width;
var height = this.height;
svg_img .attr('height', height)
.attr('width',width)
.attr('xlink:href', logoUrl)
}
d3.select("svg")
.append("image")
.attr("id", "myImage")
.attr("xlink:href", "myImage.png")
.on("load", function(d) {
var myImage = new Image();
myImage.onload = function() {
d3.select("#myImage")
.attr("width", this.width)
.attr("height", this.height);
}
myImage.src = "myImage.png";
});
It's a couple years since this has been asked but I'm currently trying to determine some things about the use of auto as a value for width or height myself and thought I would share what I've found. According to Amelia Bellamy-Royds' 2015 article on scaling SVGs and the codepen example she provides, if you put auto in as either the width or the height value of your <svg>, along with a value for the viewBox, you should be able to see the content scaling proportionately. Unfortunately, she also points out that at the time this only worked in "Blink/Firefox" browsers. Blink is a fork of part of WebKit, so it's possible that by now Chrome will support this as well. I am seeing behavior in Chrome which would seem to support this possibility, but I'm also getting an error so YMMV.