Used DC.js to create stacked bar chart with ordinal x-axis.
Versions used:
DC.js version 1.7.5
crossfilter.js version 1.3.12
D3.js version 3.5.17
The problem is that the chart's x-axis labels are not aligned with bars. They are actually shifted two ticks to right so last two labels have no bars above them.
Edit to remove - Also can't select the right most bar to filter data eg hover over bar doesn't show selector to click and activate cross filter. - it was just two chart margins overlapping blocking cursor.
Here is screenshot of chart indicating problems.
The x-axis is ordinal set using .xUnits(dc.units.ordinal)
I used a renderlet to change x-axis label orientation so they are vertical. If I remove renderlet it doesn't change the problems above.
Here is my chart div and javascript code.
<div id="month-chart"></div>
<script type="text/javascript">
d3.csv("merged_hostname.csv", function(data) {
var parseDate = d3.time.format("%Y-%m-%d").parse;
data.forEach(function(d) {
d.date = parseDate(d.date);
d.sessions = +d.sessions;
d.ad_requests = +d.ad_requests;
d.bounceRate = +d.bounceRate;
d.clicks = +d.clicks;
d.earnings = +d.earnings;
d.newUsers = +d.newUsers;
d.sessionDuration = +d.sessionDuration;
d.sessionsPerUser = +d.sessionsPerUser;
d.twitterSessions = +d.twitterSessions;
d.users = +d.users;
});
var ndx = crossfilter(data);
var yyyymmDim = ndx.dimension(function(d) { return d["yyyymm"]; });
var PPCCByYYYYMM = yyyymmDim.group().reduceSum(function(d) {
if (d.PPCC === "PPCC") {
return +d.sessions;
}else{
return 0;
}
});
var otherByYYYYMM = yyyymmDim.group().reduceSum(function(d) {
if (d.PPCC === "Other") {
return +d.sessions;
}else{
return 0;
}
});
monthChart = dc.barChart("#month-chart");
monthChart
.height(200)
.width(500)
.margins({top: 10, right: 10, bottom: 50, left: 40})
.dimension(yyyymmDim)
.group(PPCCByYYYYMM)
.stack(otherByYYYYMM)
.transitionDuration(500)
.brushOn(true)
.elasticY(true)
.yAxisLabel('sessions')
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.renderlet(function (chart) {
chart.selectAll("g.x text")
.attr('dx', '-30')
.attr('transform', "rotate(-90)");
});
dc.renderAll();
});
</script>
Any ideas what can causes these issues and how to resolve?
You can move the left position with this:
.attr('transform', "translate(-20,0) rotate(-90)");
Change 20 if its necessary
Related
I'm using Vue with Britecharts, and I've created a horizontal bar chart, and then I want to add the avatar images to the y asis on the right side of the name label. I've done some research and I've found D3 How to place image next to horizontal line text and this has done exactly what I want to achieve but in D3.
I want to know how I can do the same in Britecharts. Below is my sample code.
Codepen: https://codepen.io/cooltaiwanesesam/pen/RwPYpbz
createHorizontalBarChart() {
let barChart = new britecharts.bar(),
margin = {left: 120, right: 20, top: 20, bottom: 30},
barContainer = d3.select('.js-horizontal-bar-chart-container'),
containerWidth = barContainer.node() ? barContainer.node().getBoundingClientRect().width : false;
barChart
.isHorizontal(true)
.margin(margin)
.width(containerWidth)
.colorSchema(britecharts.colors.colorSchemas.britecharts)
.valueLabel('percentage')
.height(300);
barContainer.datum(this.data.reverse()).call(barChart);
}
Issue resolved. Sharing the code to help someone in need.
https://codepen.io/cooltaiwanesesam/pen/YzyXYWE
barChart
.isHorizontal(true)
.width(containerWidth)
.height(300);
barContainer.datum(dataset).call(barChart);
d3.selectAll('.y-axis-group .tick')
.each((d, i, list) => {
let img = barData.data.find((item) => item.name === d).img;
d3.select(list[i])
.append('image')
.attr('x', -36)
.attr('y', -22)
.attr('width', 42)
.attr('height', 42)
.attr('xlink:href', img)
});
Reference: https://github.com/eventbrite/britecharts/issues/798 Thanks to Marcos from Britecharts.
I tried to erase negative ticks from my NVD3 line chart (with data includes 0 only)
but It seems impossible what I wanted to do...
I want to set the line bottom when I throw data what includes 0 only.
Is there another way? or just I had a mistake?
code:
nv.addGraph(function() {
//DATA.B includes only 0 data, the value must be "data>0"
data = DATA.A,DATA.B;
var chart = nv.models.linePlusBarChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
.x(function(d,i) { return i })
.y(function(d,i) { return d[1] });
chart.xAxis.tickFormat(function(d) {
var dx = data[0].values[d] && data[0].values[d][0] || 0;
return d3.time.format('%Y-%m-%d')(new Date(dx))
});
chart.y1Axis
.tickFormat(d3.format(',f'))
.tickSize(0,6);
chart.y2Axis
.tickFormat(function(d) { return d3.format(',f')(d) + '%' });
chart.bars.forceY([0]);
d3.select($node).datum(data).transition().duration(0).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
thanks
I am using NVD3NVD3 to show a lineChart. The legend is very useful, and I want to enable the ability to only display a line for a single legend element, however the default configuration will transition the yAxis to be [min,max] of that legend element. I would like it to always display [0,max]. I found I can do this, however it will have a domain of 0 to max of all legend elements, not 0 to visible legened elements. Does anyone know if it is possible?
var chart = nv.models.lineChart();
var yMax = d3.max(data, function(d) {
return d3.max(d['values'], function(d2) {
return d2['open'];
});
});
chart.yDomain([0, yMax]);
UPDATE: I was able to achieve what I wanted with the following:
chart.dispatch.on('stateChange', function(e) {
var i = -1;
var yMax = d3.max(data, function(d) {
i++;
if(e.disabled[i] == false){
return d3.max(d['values'], function(d2) {
return(d2['open']);
});
}
});
chart.yDomain([0, yMax]);
});
Plnkr example:
http://plnkr.co/edit/19D5cnrVYdUrMlblQARy?p=preview
Screenshot from my app:
I've tried modifying the CSS, however I was only able to remove the 2nd (right Y axis line), but not the first left Y axis line.
What I've tried:
.nv-y {
display: none;
}
As well as all the lines from this answer: Alter first vertical grid line in nvd3
d3.selectAll('.nv-y').attr('display','none')
d3.selectAll('.nv-y path').attr('opacity','0.1')
d3.selectAll('.nv-y path').attr('display','none')
My current drawChart function:
function drawChart(res) {
console.log(' ');
console.log('drawChart res = ',res);
nv.addGraph(function() {
var chart = nv.models.linePlusBarChart()
.margin({top: 30, right: 40, bottom: 50, left: 40})
.x(function(d,i) { return i })
.y(function(d) { return d[1] })
.color(d3.scale.category10().range());
chart.xAxis.tickFormat(function(d) {
var dx = res[0].values[d] && res[0].values[d][0] || 0;
return d3.time.format('%x')(new Date(dx))
});
chart.y1Axis
.tickFormat(d3.format(',f'));
chart.y2Axis
.tickFormat(function(d) { return '$' + d3.format(',f')(d) });
chart.bars.forceY([0]);
// https://stackoverflow.com/questions/23754188/nvd3-js-how-to-disable-tooltips-for-one-serie-only
chart.lines.interactive(false);
// http://nvd3-community.github.io/nvd3/examples/documentation.html#line
chart.height(280);
// If not chart data is avaliable to display:
chart.noData("There is no Data to display at the moment.");
// Remove legend:
chart.showLegend(false);
d3.select('#chart svg')
.datum(res)
.transition().duration(500)
.call(chart);
d3.selectAll('.nv-y path').attr('display','none');
nv.utils.windowResize(chart.update);
return chart;
});
}
if you want to hide the 1st y axis do:
.nv-y1{
display:none;
}
if you want to hide the 2nd y axis do:
.nv-y2{
display:none;
}
http://plnkr.co/edit/IgFh1rV4a6ubAMe0VqT2?p=preview
Use this :
.domain {
display: none;
}
I am trying to build 2 vertical charts sharing the same data. So I created a refreshPrimary(top) and refreshStackedArea(bottom) that can be called to refresh the graphs depending on options the user selects.
The problem I am having it that when I invoke both refreshPrimary and refreshStackedArea the top graph does not show.if I only do refreshPrimary it display it's graph ok. Below are the refresh functions, the HTML and chart drawing functions.
Refresh function :
// Add refresh function to lm_pareto context
function refreshPrimary() {
//
function refreshGraph() {
console.log("DEBUG JS lm_pareto.refreshGraph entered");
d3.selectAll("#lm_pareto svg > *").remove();
d3.select('#lm_pareto svg')
.datum(lm_pareto.dataPrimary)
.call(chart);
//Update the chart when window resizes.
nv.utils.windowResize(function() { chart.update() });
return chart;
}
nv.addGraph(refreshGraph);
}
function refreshStackedArea() {
function refreshGraph_SArea() {
d3.selectAll("#lm_stackedArea svg > *").remove();
d3.select('#lm_stackedArea svg')
.datum(lm_pareto.dataStackedArea)
.call(chart); //Finally, render the chart!
//Update the chart when window resizes.
nv.utils.windowResize(function() { chart.update() });
return chart;
}
nv.addGraph(refreshGraph_SArea);
}
HTML DIV's
<div id="lm_pareto" class="lm_graph" style="border: 2px solid blue"></div>
<div id="lm_stackedArea" class="lm_graph" style="border: 2px solid blue"></div>
TOP CHART
var chart;
nv.addGraph(function () {
chart = nv.models.stackedLineChart()
.options({
reduceXTicks: false
})
.margin(margin)
// Get normalised data for chart
chart.lines1.forceY(0);
chart.lines2.forceY(0);
svg = d3.select("#lm_pareto")
.append("svg");
// chart is a temp object of nv.addGraph... not able to pass back.
return chart;
});
BOTTOM CHART
var margin = {
top: 50,
right: 50,
bottom: 50,
left: 70
};
var chart;
nv.addGraph(function() {
chart = nv.models.stackedAreaChart()
.margin(margin)
.x(function(d) { return d[0] })
.y(function(d, x) { return d[1]; })
.useInteractiveGuideline(true)
.rightAlignYAxis(false) //y-axis to the right side.
// .transitionDuration(500)
.showControls(false)
.clipEdge(true)
.color(lm_pareto.ColorList);
chart.yAxis
.tickFormat(d3.format(',.2f'));
svg = d3.select("#lm_stackedArea")
.append("svg")
// OLD WAY
//svg.datum(lm_pareto.dataStackedArea)
// .call(chart);
//
//nv.utils.windowResize(chart.update);
return chart;