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>
);
}
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With