使用D3.js(v4)和React.js如何在简单的折线图上标记轴?

问题描述 投票:5回答:1

我正在尝试使用React在D3.js的线图中添加标签。我已经编写了下面的代码,该代码将显示轴,但是文本节点不可见,但是我可以在开发人员工具的DOM中看到它。

import React, { PropTypes, Component } from 'react';
import * as d3 from 'd3';

export default class Axis extends Component {
  static propTypes= {
    h: PropTypes.number.isRequired,
    axis: PropTypes.func.isRequired,
    axisType: PropTypes.oneOf(['x', 'y']).isRequired,
  }

  componentDidMount = () => { this.renderAxis(); }

  componentDidUpdate = () => { this.renderAxis(); }

  renderAxis = () => {
    const node = this.axisRef;
    d3.select(node).call(this.props.axis);
    // const domain = d3.selectAll('path.domain');
    const ticks = d3.selectAll('g.tick');
    ticks.select('text').style('font-family', 'Poppins');
    ticks.select('text').style('fill', 'black');
  }

  render() {
    const translate = `translate(0,${(this.props.h)})`;

    return (
      <g
        ref={(node) => { this.axisRef = node; }}
        className="axis"
        transform={this.props.axisType === 'x' ? translate : ''}
      >
        <text value={this.props.axisType === 'x' ? 'x axis' : 'y axis'}>Hello world</text>
      </g>
    );
  }
}
reactjs d3.js axis
1个回答
0
投票

请参考此处的示例:https://bl.ocks.org/d3noob/23e42c8f67210ac6c678db2cd07a747e

 // Add the x Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // text label for the x axis
  svg.append("text")             
      .attr("transform",
            "translate(" + (width/2) + " ," + 
                           (height + margin.top + 20) + ")")
      .style("text-anchor", "middle")
      .text("Date");

这基本上将添加文本并将其放置在x轴的中心,即width / 2(如果有填充,则为总和)] >>

© www.soinside.com 2019 - 2024. All rights reserved.