Reactjs 如何使用react使x轴标签在d3中工作?
下面是我的代码示例:Reactjs 如何使用react使x轴标签在d3中工作?,reactjs,d3.js,labels,ordinal,Reactjs,D3.js,Labels,Ordinal,下面是我的代码示例: import React, {Component} from 'react'; import {scaleOrdinal, axisBottom, select} from 'd3'; export default class BarChart extends Component { constructor(props) { super(props) this.renderSvg = this.renderSvg.bind(this); }
import React, {Component} from 'react';
import {scaleOrdinal, axisBottom, select} from 'd3';
export default class BarChart extends Component {
constructor(props) {
super(props)
this.renderSvg = this.renderSvg.bind(this);
}
componentDidMount() {
this.renderSvg();
}
renderSvg() {
const margin = 20;
const width = 400;
const height = 800;
const data = ["why", "aren't", "you", "working"]
.map((title) => ({title}));
// create scalar for x axis
const x = scaleOrdinal()
.domain(data.map(({title}) => title))
.range([0, width]);
const xAxis = axisBottom(x);
// create svg and append graph
const svg = select("svg")
.attr("width", width)
.attr("height", height + margin)
.append("g")
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
}
render() {
const {width, height, className} = this.props;
return <div className="body">
<svg className="svg" />
</div>
}
}
import React,{Component}来自'React';
从'd3'导入{scaleOrdinal,axisBottom,select};
导出默认类条形图扩展组件{
建造师(道具){
超级(道具)
this.renderSvg=this.renderSvg.bind(this);
}
componentDidMount(){
this.renderSvg();
}
renderSvg(){
常数裕度=20;
常数宽度=400;
常数高度=800;
const data=[“为什么”、“不是”、“你”、“正在工作”]
.map((title)=>({title}));
//为x轴创建标量
常数x=scaleOrdinal()
.domain(data.map(({title})=>title))
.范围([0,宽度]);
常数xAxis=轴底(x);
//创建svg和附加图
const svg=select(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度+边距)
.附加(“g”)
svg.append(“g”)
.attr(“类”、“x轴”)
.attr(“变换”、“平移(0)”、“高度+”)
.呼叫(xAxis);
}
render(){
const{width,height,className}=this.props;
返回
}
}
我在这个网站上遵循了这个例子:据我所知,非常接近,但我无法让它以定期/偶数间隔显示标签。任何帮助都将不胜感激,我对使用d3是新手。问题是从d3v3到d3v4/5的转换
d3.scale.ordinal()
(v3)用于许多刻度类型,并由您进行的rangeX()
调用决定
在d3v5d3中,scaleOrdinal()
表示顺序比例,并将顺序域映射到顺序范围。您仅将范围设置为2值数组。因此,每个域值在2个范围值上交替
下面是一个d3v5示例。我已经调整了高度,以便在跑步时看到一些东西。使用开发工具查看轴记号的交替平移
文件
函数renderSvg(){
常数裕度=20;
常数宽度=400;
常数高度=100;
const data=[“为什么”、“不是”、“你”、“正在工作”]
.map((title)=>({title}));
//为x轴创建标量
常数x=d3.scaleOrdinal()
.domain(data.map(({title})=>title))
.范围([0,宽度]);
常数xAxis=d3.axisBottom(x);
//创建svg和附加图
const svg=d3.选择(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度+边距)
.附加(“g”);
svg.append(“g”)
.attr(“类”、“x轴”)
.attr(“变换”、“平移(0)”、“高度+”)
.呼叫(xAxis);
}
renderSvg();
将x轴转换为svg的底部像素高度
。标记和标签绘制在此位置下方。看看开发人员工具,您将看到标记和文本是svg的一部分。试试看height*0.5
问题不在于它们不可见,它们是可见的,它们只是相互重叠。这些词的间隔不是相等的,这正是我所期望的。