向 d3 条形图添加标签
-
21-12-2019 - |
题
我有一个 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 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 变量中的名称显示在计数下方。谢谢。
解决方案
以供参考:在 @bencripps 答案的评论中,OP 谈到使用 xAxis.tickValues(['One','two','three','four','five','six','seven'])
.
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)
这样它就知道使用序数标记。
其他提示
这是一个用于添加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);
.
note ,.call(xAxis)
是实际将x轴附加到图表的内容。
不隶属于 StackOverflow