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

时间:2017-07-04 09:50:24

标签: reactjs d3.js axis

我尝试使用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>
    );
  }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

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

message['chat']['id']

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