【发布时间】:2014-01-18 11:33:18
【问题描述】:
我有一个 d3 垂直条形图,我正在尝试使 x 轴标签定位正确。它几乎在那里,但不完全。标签最终偏离了条形图的中心。我还想稍微旋转一下标签,以便在需要时容纳更大的图表。
这是我的图表咖啡(里面有一些骨干木偶):
buildTimeline: ->
width = @ui.chartWrap.innerWidth()
height = @ui.chartWrap.height()
dataLength = @data.values.length
x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1)
y = d3.scale.linear()
.range([height, 0])
x.domain @data.values.map (d) ->
d.x
y.domain [0, d3.max(@data.values, (d) ->
d.y
)]
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
svg = d3.select(@ui.chartWrap[0]).append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', '0,0')
svg.append("g")
.attr('id', 'timeline-labels')
.attr("transform", "translate(0,#{height-20})")
.call(xAxis)
# Bars
svg.append('g')
.attr('id', 'timeline-bars')
.selectAll(".bar")
.data(@data.values)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d) ->
x(d.x)
)
.attr("width", 25)
.attr("y", (d) ->
y(d.y) - 30
)
.attr("height", (d) =>
height - y(d.y)
).attr("data-date", (d) =>
d.x
).attr("data-count", (d) =>
d.y
)
然后这是我的图表示例 JSON:
{
"key": "Documents",
"values": [
{
"x": "1980",
"y": 1752
},
{
"x": "1981",
"y": 0
},
{
"x": "1982",
"y": 0
},
{
"x": "1983",
"y": 0
},
{
"x": "1984",
"y": 0
},
{
"x": "1985",
"y": 0
},
],
"type": "year"
}
最后的图表快到了,但现在所有标签都堆积在一根柱子下:
【问题讨论】:
-
您不使用您正在创建的轴的任何原因?
svg.append("g").call(xAxis)(带有一些翻译)应该注意标签的定位。 -
老实说,我继承了这段代码,而且我对 d3 还很陌生。如何使用 xAxis?
-
就像我上面概述的那样。您追加一个
g元素,然后追加.call(xAxis)。 -
添加
svg.append('g').call(xAxis)在画布中创建一个g,它具有domain类和d属性,但没有值。它所做的只是在我的图表顶部产生一个奇怪的黑条:cl.ly/image/1O040U1T0l0L -
是的,你必须做一些造型等。参见例如this tutorial.
标签: javascript charts d3.js