Reputation: 407
I'm building a graph visualization based on chart.js library. I'm allowing the user to change from a linear to a radar type of graph, based on the selection of a select combobox. When going from a line chart to a radar, and back, both of the linear and radial axis are displaying. I tried to look for a "Clear axis" function but couldn't find one.
Is there any way to force redrawing the correct axis based on a chart type ?
You can find an example here.
Here's my basic HTML and JS/JQuery code :
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<select id="chartType0">
<option value="line">Line</option>
<option value="radar">Radar</option>
</select>
<canvas id="chart0"></canvas>
JQuery :
$(function() {
$("#chartType0").change(function() {
var type = $("#chartType0 option:selected").val();
var chartObj = $("#chart0").data("graph");
chartObj.config.type = type;
chartObj.update();
});
var ctx = $("#chart0");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgb(255, 99, 132)',
data: [5, 10, 5, 7, 20, 30, 45]
}]
}
});
ctx.data("graph", chart);
});
Upvotes: 1
Views: 339
Reputation: 14433
It seems that the update
method works only with new data. For new types you will need to create a new chart every time.
$(function() {
$("#chartType0").change(function() { createChart($(this).val()) })
function createChart(type) {
new Chart($("#chart0"), {
type: type,
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgb(255, 99, 132)',
data: [5, 10, 5, 7, 20, 30, 45]
}]
}
})
}
createChart('line')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<select id="chartType0">
<option value="line">Line</option>
<option value="radar">Radar</option>
</select>
<canvas id="chart0"></canvas>
Upvotes: 1