使用 D3.js (v4) 和 React.js 如何在简单的折线图上标记轴?
Using D3.js (v4) and React.js How do I label the axis on a simple line chart?
我正在尝试使用 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>
);
}
}
参考这里的例子: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(如果有的话加上填充)
我正在尝试使用 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>
);
}
}
参考这里的例子: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(如果有的话加上填充)