我第一次使用d3并尝试在React应用程序中渲染条形图。该代码正确生成了元素,和(group),但不会根据提供的数据在de group元素内生成“ rect”元素。 ¿能否请您指出问题出在哪里?d3没有在
内附加“ rect”如果我在de里面手动添加了一个'rect',它将起作用。但是当我添加使用.data(data).enter()时,没有显示条形图。
到目前为止,这些是代码生成的元素:
<div class="bargraph">
<svg width="700" height="500">
<defs>
<linearGradient id="svgGradient" x1="0%" x2="100%" y1="0%" y2="0%">
<stop class="start" offset="0%" stop-color="red" stop-opacity="1"> </stop>
<stop class="end" offset="100%" stop-color="blue" stop-opacity="1"></stop>
</linearGradient>
</defs>
<g></g>
</svg>
</div>
这是代码:
import React from 'react';
import * as d3 from "d3";
function Bargraph(data){
let padding = 10;
let barHeight = 46;
let outerWidth = 700;
let yScale = d3.scaleLinear().range([0,153]);
yScale.domain([0,d3.max(data, (d)=>parseFloat(d[1]))])
var svg = d3.select('.bargraph').append('svg').attr('width', 700).attr('height', 500);
var definitions = svg.append('defs');
var gradient = definitions.append("linearGradient")
.attr("id", "svgGradient")
.attr("x1", "0%")
.attr("x2", "100%")
.attr("y1", "0%")
.attr("y2", "0%");
gradient.append('stop')
.attr('class', 'start')
.attr("offset", "0%")
.attr("stop-color", "red")
.attr("stop-opacity", 1);
gradient.append("stop")
.attr('class', 'end')
.attr("offset", "100%")
.attr("stop-color", "blue")
.attr("stop-opacity", 1);
var barGroup = svg.append('g');
var bars = barGroup.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr("fill", "url(#svgGradient)")
.attr('width', 30)
.attr('height', barHeight - 10);
return(
<div className="bargraph">
</div>
)
}
export default Bargraph;
我希望在组内获得一个水平条形图,以便对条形集应用转换,然后添加轴。
添加了评论: 我的数据是对从类组件传递的组件的支持。
Statistics.js
import React from 'react';
import Bargraph from "../Bargraph/Bargraph.js";
class Statistics extends React.Component{
constructor(props){
super(props);
this.state= {
data:[
["vocalist", "10"],
["producer", "15"],
["composers", "18"],
["engineers", "8"],
["instrumentalist", "15"],
["arrangers", "10"],
["artDirectors", "17"],
["albumNotes", "10"],
["narrators", "6"],
["musicDirectors", "12"]
],
}
}
render(){
return(
<Bargraph data={this.state.data}/>
)
}
}