d3 axis labeling

d3 axis labeling

本文关键字:labeling axis d3      更新时间:2023-09-26

如何在 d3 中向轴添加文本标签?

例如,我有一个带有 x 和 y 轴的简单折线图。

在我的 x 轴上,我有从 1 到 10 的刻度。我希望"天"这个词出现在它下面,这样人们就知道x轴正在计算天数。

同样,在 y 轴上,我有数字 1-10 作为刻度,我希望"吃的三明治"这个词侧向出现。

有没有简单的方法可以做到这一点?

轴标签不是内置于 D3 的轴组件中,但您只需添加 SVG text元素即可自行添加标签。一个很好的例子是我对Gapminder的动画气泡图《国家的财富与健康》(The Wealth & Health of Nations)的再创作。x 轴标签如下所示:

svg.append("text")
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width)
    .attr("y", height - 6)
    .text("income per capita, inflation-adjusted (dollars)");

y 轴标签如下所示:

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("life expectancy (years)");

您还可以使用样式表来根据需要设置这些标签的样式,可以一起(.label)或单独(.x.label.y.label)。

在新的 D3js 版本(版本 3 及更高版本)中,当您通过函数创建图表轴时d3.svg.axis()您可以访问函数中内置的名为 tickValuestickFormat 的两个方法,以便您可以指定需要刻度的值以及您希望文本以什么格式显示:

var formatAxis = d3.format("  0");
var axis = d3.svg.axis()
        .scale(xScale)
        .tickFormat(formatAxis)
        .ticks(3)
        .tickValues([100, 200, 300]) //specify an array here for values
        .orient("bottom");

如果你想像我一样在 y 轴的中间显示 y 轴标签:

  1. 使用文本锚点中间将文本旋转 90 度
  2. 按中点翻译文本
    • x 位置:防止 y 轴刻度标签重叠 ( -50
    • y
    • 位置:匹配 y 轴的中点 ( chartHeight / 2

代码示例:

var axisLabelX = -50;
var axisLabelY = chartHeight / 2;
chartArea
    .append('g')
    .attr('transform', 'translate(' + axisLabelX + ', ' + axisLabelY + ')')
    .append('text')
    .attr('text-anchor', 'middle')
    .attr('transform', 'rotate(-90)')
    .text('Y Axis Label')
    ;

这样可以防止旋转整个坐标系,如上面提到的 lubar 所示。

如果您按照

建议在 d3.v4 中工作,则可以使用此实例提供所需的一切。

您可能只想将 X 轴数据替换为"天",但请记住正确解析字符串值,不要应用连接。

parseTime 不妨使用日期格式缩放天数?

d3.json("data.json", function(error, data) {
if (error) throw error;
data.forEach(function(d) {
  d.year = parseTime(d.year);
  d.value = +d.value;
});
x.domain(d3.extent(data, function(d) { return d.year; }));
y.domain([d3.min(data, function(d) { return d.value; }) / 1.005, d3.max(data, function(d) { return d.value; }) * 1.005]);
g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

g.append("g")
    .attr("class", "axis axis--y")
    .call(d3.axisLeft(y).ticks(6).tickFormat(function(d) { return parseInt(d / 1000) + "k"; }))
  .append("text")
    .attr("class", "axis-title")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .attr("fill", "#5D6971")
    .text("Population)");

摆弄全局CSS/JS

D3 提供了一组非常低级别的组件,可用于组合图表。您将获得构建块、轴组件、数据连接、选择和 SVG。你的工作是把它们放在一起形成一个图表!

如果你想要一个传统的图表,即一对轴,轴标签,图表标题和一个绘图区,为什么不看看d3fc? 它是一组更高级的 D3 组件的开源集合。它包括一个笛卡尔图组件,这可能是您需要的:

var chart = fc.chartSvgCartesian(
    d3.scaleLinear(),
    d3.scaleLinear()
  )
  .xLabel('Value')
  .yLabel('Sine / Cosine')
  .chartLabel('Sine and Cosine')
  .yDomain(yExtent(data))
  .xDomain(xExtent(data))
  .plotArea(multi);
// render
d3.select('#sine')
  .datum(data)
  .call(chart);

您可以在此处查看更完整的示例:https://d3fc.io/examples/simple/index.html

chart.xAxis.axisLabel('Label here');

xAxis: {
   axisLabel: 'Label here'
},

在 D3.js
中自定义轴https://ghenshaw-work.medium.com/customizing-axes-in-d3-js-99d58863738b

let xAxisGenerator = d3.axisBottom(xScale);
let tickLabels = ['A','B','C'];
xAxisGenerator.tickFormat((d,i) => tickLabels[i]);