When I try to update my d3 graph after selecting a site from the dropdown menu, a new graph is generated and I can't figure out how to remove the old one.
https://i.sstatic.net/R5BNE.png
Below is the code within the script tags:
<script>
import * as d3 from 'd3'
import { rgbaToHex } from '../utils/color.ts'
export default {
data () {
return {
selectedSite: '',
selectedWhale: '',
groupType: '',
heatmapShow: false
}
},
mounted () {
this.generateChart()
},
methods: {
generateChart () {
// set the dimensions and margins of the graph
const margin = { top: 20, right: 20, bottom: 30, left: 30 }
const width = 1850 - margin.left - margin.right
const height = 200 - margin.top - margin.bottom
// create an area for the graph
const svg = d3.select('#heatmap')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.bottom})`)
// define x and y labels
const xLabel = d3.range(259)
const yLabel = d3.range(23, -1, -1)
const x = d3.scaleBand()
.domain(xLabel)
.range([0, width])
.padding(0.05)
svg.append('g')
.attr('transform', `translate(0, ${height})`)
.call(d3.axisBottom(x).tickValues(x.domain().filter((_, i) => !(i % 6))))
const y = d3.scaleBand()
.domain(yLabel)
.range([height, 0])
.padding(0.05)
svg.append('g').call(d3.axisLeft(y).tickValues(y.domain().filter((_, i) => !(i % 5))))
d3.json('../predictions.json').then((data) => {
const u = svg.selectAll().data(data.heatmaps[this.selectedWhale][this.selectedSite])
u.exit().remove()
const uEnter = u.enter().append('rect')
uEnter
.merge(u)
.transition()
.duration(1000)
.attr('x', function (d) {
return x(d[1])
})
.attr('y', function (d) {
return y(d[0])
})
.attr('cx', 1)
.attr('cy', 1)
.attr('width', x.bandwidth())
.attr('height', y.bandwidth())
.style('fill', function (d) {
return rgbaToHex(0, 128, 255, 100 * d[2])
})
.on('mouseover', function () {
d3.select(this)
.style('stroke', 'black')
.style('opacity', 1)
})
.on('mouseout', function () {
d3.select(this)
.style('stroke', 'none')
.style('opacity', 0.8)
})
.on('click', (d) => {
console.log(d)
this.heatmapShow = true
})
uEnter.exit().remove()
})
}
},
watch: {
selectedSite: function () {
this.generateChart()
},
selectedWhale: function () {
this.generateChart()
},
groupType: function (value) {
console.log(value)
}
}
}
</script>