Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using D3.js (v4) and React.js How do I label the axis on a simple line chart?

Im trying to add labels to my linechart on D3.js using React. I have written the code below which will display the axis but the text node is not visible but I can see it in the DOM in the developer tools.

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>
    );
  }
}
like image 304
Tormod Smith Avatar asked Nov 07 '22 20:11

Tormod Smith


1 Answers

Refer to the example here: 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");

This will basically add up a text and and place it in the center of x-axis i.e. width/2 (sum with padding if any)

like image 55
Aqua 4 Avatar answered Nov 15 '22 06:11

Aqua 4