我是 D3-v5 的新手,正在尝试使用更新按钮(随机值)创建条形图。我按照下面的代码创建了所有东西,
<body>
<button onclick="updateData()">Update</button>
<!-- Bar Chart for SVG-->
<svg width ="500" height="500" id="svg2">
</svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
//Bar Chart
//Creating data
let data2 = [
{name: 'A', value: Math.floor(Math.random() * 100)},
{name: 'B', value: Math.floor(Math.random() * 100)},
{name: 'C', value: Math.floor(Math.random() * 100)},
{name: 'D', value: Math.floor(Math.random() * 100)},
{name: 'E', value: Math.floor(Math.random() * 100)},
{name: 'F', value: Math.floor(Math.random() * 100)},
{name: 'G', value: Math.floor(Math.random() * 100)},
{name: 'H', value: Math.floor(Math.random() * 100)},
{name: 'I', value: Math.floor(Math.random() * 100)},
{name: 'J', value: Math.floor(Math.random() * 100)}
]
//Creating svg, margin, width, height
let svg2 = d3.select("#svg2")
let margin = 30;
let width = 500 - 2 * margin;
let height = 500 - 2 * margin;
//Creating chart by using g in svg2.
let chart2 = svg2.append('g')
.attr('transform', 'translate(30, 30)');
//yScale
let yScale2 = d3.scaleLinear()
.range([height, 0])
.domain([0, 100]);
//append g to create y axis
chart2.append('g')
.call(d3.axisLeft(yScale2));
//xScale
let xScale2 = d3.scaleBand()
.range([0, width])
.domain(data2.map((d) => d.name))
.padding(0.2);
//append g to create x axis
chart2.append('g')
.attr('transform', 'translate(0, 440)')
.call(d3.axisBottom(xScale2));
//Creating color scale using scaleOrdinal and schemeCategory10
let colorScale = d3.scaleOrdinal(d3.schemeCategory10)
但是,当我按下 HTML 中的更新按钮时,它会转换并重叠图表,如下图所示,
唯一需要更改的是条形图,但所有条形图都在随值转换。所以我试图从网上谷歌它找出,但找不到它..
我需要编辑或添加哪些内容..?
有人可以帮我吗?
波斯汪
相关分类