Issue
I'd like to plot a backwards-bending line using chart.js.
For example: the equation x=-(y-1)**2+1
should create this graph:
I'm using python and flask for my webpage. The code that generates the graph data inside the flask route looks like this:
@bp.route('/chart', methods=('GET',))
def chart():
y = np.linspace(0, 2, 10).tolist()
x = [-(i-1)**2+1 for i in y]
return render_template(
'chart.html',
x=x,
y=y
)
And my HTML file looks like this:
<div>
<meta id="x" data-x="{{ x }}">
<meta id="y" data-y="{{ y }}">
<canvas id="chart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
const canvas = document.getElementById('chart');
const x = JSON.parse(document.getElementById('x').getAttribute('data-x'));
const y = JSON.parse(document.getElementById('y').getAttribute('data-y'));
new Chart(canvas, {
type: 'line',
data: {
labels: x,
datasets: [{
label: 'Backwards-Bending Line',
data: y,
borderWidth: 1
}]
},
})
</script>
This code creates the following graph:
You can see the x-axis increases and then decreases instead of wrapping the line backwards. How can I get the line to bend backwards?
Solution
In the Chart.js
configuration, you should get rid of data.labels
and instead define datasets.data
as an array
of objects, having an x
and y
property each.
A simplified result for your case would look as follows:
new Chart('chart', {
type: 'line',
data: {
datasets: [{
label: 'Backwards-Bending Line',
data: [
{x: 0, y: 20},
{x: 5, y: 15},
{x: 8, y: 10},
{x: 5, y: 5},
{x: 0, y: 0}
],
borderWidth: 1,
tension: 0.3
}]
},
options: {
responsive: false,
aspectRatio: 1,
scales: {
x: {
type: 'linear'
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@^4"></script>
<canvas id="chart" width="200"></canvas>
Please also consult Data Structures > Object[] from the Chart.js
documentation.
Answered By - uminder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.