Javascript 向d3条形图添加标签
我有一个d3柱状图,我从firebase中提取数据。我想将标签添加到x轴。以下是我的条形图的代码:Javascript 向d3条形图添加标签,javascript,d3.js,firebase,dc.js,Javascript,D3.js,Firebase,Dc.js,我有一个d3柱状图,我从firebase中提取数据。我想将标签添加到x轴。以下是我的条形图的代码: new Firebase('https://exampl.firebaseIO.com/example').on('value', function (snapshot) { var lst = []; snapshot.forEach(function(childSnapshot) {lst.push(childSnapshot.val());}); var magVal
new Firebase('https://exampl.firebaseIO.com/example').on('value', function (snapshot) {
var lst = [];
snapshot.forEach(function(childSnapshot) {lst.push(childSnapshot.val());});
var magValue = new crossfilter(lst).dimension(function (d) {return d.count;});
var magLabel = new crossfilter(lst).dimension(function (d) {return d.Owner;});
dc.barChart("#dc-magnitude-chart")
.width(480)
.height(150)
.margins({top: 10, right: 10, bottom: 20, left: 40})
.dimension(magValue) // the values across the x axis
.group(magValue.group().reduceSum(function(d) {return d.count;})) // the values on the y axis
.transitionDuration(500)
.centerBar(true)
.gap(56) // bar width Keep increasing to get right then back off.
.x(d3.scale.linear().domain([0.5, 7.5]))
.elasticY(true)
.xAxis().tickFormat(function(v) {return v;});
dc.renderAll();
});
magValue是发生的简单计数,它显示在x轴上。我希望存储在magLabel变量中的名称显示在计数下方。谢谢。这里是一些添加X轴的简单代码;您必须修改域和范围以获得所需的长度和刻度数
var XaxisScale = d3.scale.linear()
.domain([0,150]) //you will have to set the domain, not sure what you want
.range([0, magValue.length)
var xAxis = d3.svg.axis()
.scale(XaxisScale)
.ticks( magValue.length ) // this you will need to set as well
var xAxisGroup = $('"#dc-magnitude-chart').append("g")
.attr('class', 'axis')
.attr('transform', 'translate(5,8)')
.call(xAxis);
注意,
.call(xAxis)
实际上是将X轴添加到图表中。参考:在@bencripps答案的评论中,OP讨论了使用xAxis.tickValues(['1','2','3','4','5','6','7')
tickValues
实际上是指您想在使用的刻度内指定自定义刻度。现在,您使用的是线性比例:
.x(d3.scale.linear().domain([0.5, 7.5]))
因此,它希望您的刻度值是可以绘制刻度的刻度上的点。如果您有更像xAxis.tickValues([1,2,3,4,5,6,7])
,它应该可以工作
然而,听起来你实际上并不想要线性比例。d3还有其他类型的音阶,听起来你想要的是一个。序数刻度是您通常认为用于条形图的刻度;它们是一种具有离散域的尺度。在这种情况下,您可以尝试将比例更改为:
.x(d3.scale.ordinal().domain(['One','two','three','four','five','six','seven']))
因此,它使用了序数刻度。因为您使用的是dc.js,所以还需要指定
.xUnits(dc.units.ordinal)
这样它就知道如何使用序数标记。我的代码创建了一个以数字作为刻度值的轴。我尝试使用文本作为刻度值。文本存储在magLabel变量中。我一直在浏览dc.js文档,其中有一个命令`xAxis.tickValues([])。我试图使用它,但无法使其工作。你的回答没有回答我的问题,但是谢谢你的努力。你能把你用
tickValues尝试过的东西和在OP中出错的地方都包括进来吗?@MikePrecup首先,我注释掉xAxis.tickFormat()
,然后添加这个xAxis.tickValues(['1','2','3','4','5','6','7'))
根本不显示刻度。如果我不注释掉xAxis.tickFormat()
图表就会呈现。图表中有七个条形图。dc 2.0将推导域值,因此您不必指定它们。