Django creating radar chart with Json - javascript

I created a system with Django. I need some charts for my project and I am using chart.js library.
I get data from an API address, I can get the data correctly with Json and display it in a table, but I can not display it in the radar chart.
I think I cannot write Javascript code correctly because Radar chart does not show anything.
views.py
def Radar(request):
response = requests.get('https://api.f-rayscoring.com/company/ADESE/radar')
data = response.json()
return render(request, 'radar.html', {'data': data})
radar.html
<div class="content">
<div class="page-inner">
<h4 class="page-title">Radar Chart</h4>
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<div class="card-title">Radar Chart</div>
</div>
<div class="card-body">
<div class="chart-container">
<canvas id="radarChart"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block javascripts %}
<script src="/static/assets/js/setting-demo2.js"></script>
<script>
radarChart = document.getElementById('radarChart').getContext('2d')
{% for dt in data %}
var myRadarChart= new Chart(radarChart, {
type: 'radar',
data: {
labels: [{{ dt.title }}],
datasets: [{
data: [{{ dt.value }}],
borderColor: '#1d7af3',
backgroundColor : 'rgba(29, 122, 243, 0.25)',
pointBackgroundColor: "#1d7af3",
pointHoverRadius: 4,
pointRadius: 3,
label: 'Team 1'
}, {
data: [],
borderColor: '#716aca',
backgroundColor: 'rgba(113, 106, 202, 0.25)',
pointBackgroundColor: "#716aca",
pointHoverRadius: 4,
pointRadius: 3,
label: 'Team 2'
},
]
},
options : {
responsive: true,
maintainAspectRatio: false,
legend : {
position: 'bottom'
}
}
});
{% endfor %}
my api
[{"title":"Verimlilik","value":0.5},{"title":"Likidite","value":0.7},{"title":"Kaldıraç","value":2.7},{"title":"Karlılık","value":1.55},{"title":"Büyüme","value":1.5}]
All data in this api should display in 1 radar chart.

Related

Javascript doesn't execute when the html is called by a hx-get

I have the following html's that i load in a Django app:
pie_chart.html
{% load i18n %}
<div id="chartcontainer" >
<div style= "width: 400px;" "height: 400px;">
<canvas id="pie-chart"></canvas>
<b>Balance: </b> {{balance}}<br>
</div>
<div>
<h5>Detail group:
<select name="group" id="group"
hx-get="groupdetail/"
hx-trigger="click changed delay:1s"
hx-target="#groupchart"
hx-include="[name='year']"
hx-swap="innerHTML"
>}
{% for l in labels %}
{% if l == groupcode %}
<option value={{l}} selected>{{l}}</option>
{% else %}
<option value={{l}}>{{l}}</option>
{% endif %}
{% endfor %}
</select>
</h5>
</div>
<div id=groupchart>
{% include 'bar_chart.html' %}
</div>
</div>
<script>
var config_pie = {
type: 'pie',
data: {
datasets: [{
data: {{ data|safe }},
backgroundColor: {{ backgroundcolor|safe }},
label: 'Amount_EUR',
}],
labels: {{ labels|safe }}
},
options: {
responsive: true
}
};
var ctx_pie = document.getElementById('pie-chart').getContext('2d');
window.myPie = new Chart(ctx_pie, config_pie);
</script>
bar_chart.html
{% load i18n %}
<div>
<div style= "width: 400px;" "height: 400px;">
<canvas id="group-chart"></canvas>
<b>Balance: </b> {{groupbalance|safe}} <br>
<p id="data"> her should com the config_bar var</p>
</div>
</div>
<script>
var config_bar = {
type: 'bar',
data: {
datasets: [{
data: {{ groupdata|safe }},
backgroundColor: {{ backgroundcolor|safe }},
label: 'Amount_EUR',
}],
labels: {{ grouplabels|safe }}
},
options: {
indexAxis: 'y',
responsive: true
}
};
var ctx_bar = document.getElementById('group-chart').getContext('2d');
window.myBar = new Chart(ctx_bar, config_bar);
document.getElementById("data").innerHTML = config_bar;
</script>
When the bar_chart.html is called by the {% include 'bar_chart.html' %}, the script is executed and the chart is properly displayed.
When the bar_chart.html is called by the Django view called with hx-get="groupdetail/", the script is not executed. The html is displayed, but the graph is not build, because the script is not executing.
Already 2 days now I'm breaking my head on this and searching internet for an answer.
If someone could tell me why this is happening, it would be great.
I tried to put the html that has to be replace in and without , change hx-swap="innerHTML" for hx-swap="outerHTML", but nothing changes.
I found what the problem was. When loading the 'bar_chart.html' with hx-get I didn't define the 'backgroundcolor' variable. This missing variable blocked the execution of the script.
I will also look further how I can use the suggestion made by 'mariodev'.
Thanks for the suggestion.

I can't show the values of my database in a graph using chartjs

I'm trying to practice with chartjs, so I've downloaded some code from the Internet to adapt it to my needs.
I need to display the number of patients who were born in a specific month based on their dates of birth as well as their year of birth.
The issue is that I have searched for every way to display the information that I have in my database in the graph and I can't find the way, since the code of the graphs is in an external javascript file.
I have been trying to solve this for a long time, please, I would really appreciate it if someone could help me
table Pacients
CREATE TABLE `pacients` (
`id` int(11) NOT NULL,
`first_name` varchar(30) COLLATE utf8_spanish_ci NOT NULL,
`last_name` varchar(30) COLLATE utf8_spanish_ci NOT NULL,
`document_name` varchar(20) COLLATE utf8_spanish_ci NOT NULL,
`document_numb` int(12) NOT NULL,
`phone` int(16) NOT NULL,
`sex` varchar(10) COLLATE utf8_spanish_ci NOT NULL,
`pregncy` varchar(2) COLLATE utf8_spanish_ci NOT NULL,
`date_birth` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
INSERT INTO `pacients` (`id`, `first_name`, `last_name`, `document_name`, `document_numb`, `phone`, `sex`, `pregnancy`, `date_birth`) VALUES
(6, 'marta', 'mangue', 'DNI', 655, 222987665, 'Feminine', '', '2021-12-28', '', '', ''),
(7, 'Mayo', 'Esono', 'DNI', 5769, 551233234, 'Masculine', '', '2021-10-25', '', '', ''),
(40, 'Celso', 'NUESTRA', 'Passport', OF4334, 4343, 'Masculine', '', '2021-11-19', '', '', ''),
(41, 'Nathan', 'Narby Esimi', 'passport', P001111, 654890, 'Masculine', '', '2021-12-28', '', '', '');
chart.js
var myChart = new Chart(ctxGreen, {
type: 'line',
data: data,
options: gradientChartOptionsConfigurationWithTooltipGreen
});
This is where I would like my information to appear
var chart_labels = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var chart_data = [100, 70, 90, 70, 85, 60, 75, 60, 90, 80, 110, 100];
var ctx = document.getElementById("chartBig1").getContext('2d');
var gradientStroke = ctx.createLinearGradient(0, 230, 0, 50);
gradientStroke.addColorStop(1, 'rgba(72,72,176,0.1)');
gradientStroke.addColorStop(0.4, 'rgba(72,72,176,0.0)');
gradientStroke.addColorStop(0, 'rgba(119,52,169,0)'); //purple colors
var config = {
type: 'line',
data: {
labels: chart_labels,
datasets: [{
label: "My First dataset",
fill: true,
backgroundColor: gradientStroke,
borderColor: '#d346b1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: chart_data,
}]
},
options: gradientChartOptionsConfigurationWithTooltipPurple
};
var myChartData = new Chart(ctx, config);
$("#polio").click(function() {
var data = myChartData.config.data;
data.datasets[0].data = chart_data;
data.labels = chart_labels;
myChartData.update();
});
$("#sarampion").click(function() {
var chart_data = [80, 120, 105, 110, 95, 105, 90, 100, 80, 95, 70, 120];
var data = myChartData.config.data;
data.datasets[0].data = chart_data;
data.labels = chart_labels;
myChartData.update();
});
$("#paludismo").click(function() {
var chart_data = [60, 80, 65, 130, 80, 105, 90, 130, 70, 115, 60, 130];
var data = myChartData.config.data;
data.datasets[0].data = chart_data;
data.labels = chart_labels;
myChartData.update();
});
var ctx = document.getElementById("CountryChart").getContext("2d");
var gradientStroke = ctx.createLinearGradient(0, 230, 0, 50);
gradientStroke.addColorStop(1, 'rgba(29,140,248,0.2)');
gradientStroke.addColorStop(0.4, 'rgba(29,140,248,0.0)');
gradientStroke.addColorStop(0, 'rgba(29,140,248,0)'); //blue colors
index.php this is the php file where the graph is displayed
<?php include("plantillas/header.php"); ?>
<section class="panelControl">
<div class="container">
<div class="row">
<div class="col-12 titulo-panel">
<h2 class="card-title">Administration panel</h2>
<p>Check patient statistics</p>
<div class="container">
<div class="content">
<div class="row">
<div class="col-12">
<div class="card custom-card">
<div class="card-header ">
<div class="row">
<div class="col-sm-6 text-left">
<h5 class="card-category">Pacients</h5>
<h2 class="card-title">Statistics of registered patients</h2>
</div>
<div class="col-sm-6">
<div class="btn-group btn-group-toggle float-right" data-toggle="buttons">
<label class="btn btn-sm btn-primary btn-simple active" id="Poliomyelitis">
<input type="radio" name="options" checked>
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block">Poliomyelitis</span>
<span class="d-block d-sm-none">
<i class="tim-icons icon-single-02"></i>
</span>
</label>
<label class="btn btn-sm btn-primary btn-simple" id="Measles">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block">Measles</span>
<span class="d-block d-sm-none">
<i class="tim-icons icon-gift-2"></i>
</span>
</label>
<label class="btn btn-sm btn-primary btn-simple" id="Malaria">
<input type="radio" class="d-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block">Malaria</span>
<span class="d-block d-sm-none">
<i class="tim-icons icon-tap-02"></i>
</span>
</label>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="chart-area">
<canvas id="chartBig1"></canvas>
</div>
</div>
</div>
</div>
</div>
I have searched for solutions by looking at various tutorials but so far I have not found any that help me

Multiple Chart.js charts on a single page, from 1 function but different data

Thank you for viewing my question.
I have multiple charts I need to display on a single page, the values need to be in the HTML, hence the JavaScript retrieving them.
The issue I have is both charts are retrieving the same data, caused by querySelectorAll('.myChart-values .value') I need to fetch only the values in the bulleted list under the chart, I found the following question: Chart.js: One function for multiple graphs but the code is slightly different to mine. I believe I need to iterate over each chart which I'm doing here for (const chart of Array.from(charts)) { then could I do something like closest or children to retrieve the relevant values? or perhaps I need to put a data attribute on the <canvas class="myChart"></canvas>.
Help with this would be most grateful.
let chartDataValues = [];
const chartValues = document.querySelectorAll('.myChart-values .value');
for (const chartValue of Array.from(chartValues)) {
chartDataValues.push(chartValue.innerHTML);
}
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const data = {
labels: labels,
datasets: [{
data: chartDataValues,
backgroundColor: [
'rgba(17, 39, 61, 1)',
'rgba(2, 113, 184, 1)',
'rgba(196, 226, 247, 1)',
'rgba(0, 159, 227, 1)',
'rgba(0, 130, 180, 1)',
'rgba(234, 236, 236, 1)'
]
}]
};
const config = {
type: 'bar',
data: data,
options: {
plugins: {
legend: {
display: false
},
},
scales: {
x: {
grid: {
display: false
}
},
y: {
beginAtZero: true,
grid: {
display: false
}
}
}
}
};
const charts = document.querySelectorAll('.myChart');
for (const chart of Array.from(charts)) {
const myChart = new Chart(
chart,
config
)
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.1/dist/chart.min.js"></script>
<!-- Chart JS -->
<section class="section--padding">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="content">
<canvas class="myChart"></canvas>
</div>
</div>
<div class="col-md-4">
<div class="content">
<ul class="myChart-values">
<li>
<span class="value">10</span>%
</li>
<li>
<span class="value">16</span>%
<li>
<span class="value">10</span>%
</li>
<li>
<span class="value">10</span>%
</li>
<li>
<span class="value">14</span>%
</li>
<li>
<span class="value">18</span>%
</li>
</ul>
</div>
</div>
</div>
</div>
</section>
<!-- Chart JS -->
<section class="section--padding">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="content">
<canvas class="myChart"></canvas>
</div>
</div>
<div class="col-md-6">
<div class="content">
<ul class="myChart-values">
<li>
<span class="value">2</span>%
</li>
<li>
<span class="value">10</span>%
<li>
<span class="value">10</span>%
</li>
<li>
<span class="value">20</span>%
</li>
<li>
<span class="value">30</span>%
</li>
<li>
<span class="value">15</span>%
</li>
</ul>
</div>
</div>
</div>
</div>
</section>
As you said you would to have differents data, you can say
const data1 = {
labels: labels,
datasets: [{
data: chartDataValues,
backgroundColor: [
'rgba(17, 39, 61, 1)',
'rgba(2, 113, 184, 1)',
'rgba(196, 226, 247, 1)',
'rgba(0, 159, 227, 1)',
'rgba(0, 130, 180, 1)',
'rgba(234, 236, 236, 1)'
]
}]
};
and
const data2 = {
labels: labels,
datasets: [];
Then what you need is to make two config. Config1 and Config2.
With data: data1 for Config1, and data: data2 for config2.

Determining which chart the user has clicked on

I'm using chart.js to draw multiple line charts. And when the user clicks on one of these charts, I need to know which chart it was. In order to catch the click of the user, I've added events: ['click'] in the options of the chart, as well as a onClick: clicked to call the function clicked when the user has clicked on the chart. Now I have this:
let chLine = document.getElementById("chLine");
let chartData = {
labels: ['l1', 'l2', 'l3', 'l4', 'l5', 'l6', 'l7', 'l8', 'l9'],
datasets: [
{
label: 'c1',
data: [0.3, 0.4, 0.5, 0.35, 0.2, 0.5, 0.4, 0.55, 0.6],
backgroundColor: 'transparent',
borderColor: '#e6194b',
borderWidth: 1,
pointBackgroundColor: '#e6194b'
},
{
label: 'c2',
data: [0.7, 0.5, 0.2, 0.4, 0.6, 0.1, 0.88, 0.35, 0.45],
backgroundColor: 'transparent',
borderColor: '#3cb44b',
borderWidth: 1,
pointBackgroundColor: '#3cb44b'
}
]
}
if (chLine) {
new Chart(chLine,{
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
position: 'top',
labels: {
boxWidth: 5
}
},
events: ['click'],
onClick: clicked
}
}
);
}
function clicked(c, i) {
console.log(c, i)
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div class="row my-3">
<div class="col">
<h4>Chart</h4>
</div>
</div>
<div class="row my-2">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<canvas id="chLine" height="100"></canvas>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<script src="test.js"></script>
</body>
</html>
And every time I click on a chart, it gives an array containing information about each chart and also an object containing information about the click event. But I can't seem to find information to conclude which chart was clicked. How can I do this?
Inside the clicked function you can use getElementAtEvent(c) & _datasetIndex; to get the index of the chart data.After that use that index to get the data which is used to draw that line chart. In this example another field is added to the data and on click that name field is consoled. In this case you need to click on the chart circle
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<div class="container">
<div class="row my-3">
<div class="col">
<h4>Chart</h4>
</div>
</div>
<div class="row my-2">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<canvas id="chLine" height="100"></canvas>
</div>
</div>
</div>
</div>
</div>
let chLine = document.getElementById("chLine");
let chartData = {
labels: ['l1', 'l2', 'l3', 'l4', 'l5', 'l6', 'l7', 'l8', 'l9'],
datasets: [{
name: 'First Chart',
label: 'c1',
data: [0.3, 0.4, 0.5, 0.35, 0.2, 0.5, 0.4, 0.55, 0.6],
backgroundColor: 'transparent',
borderColor: '#e6194b',
borderWidth: 1,
pointBackgroundColor: '#e6194b'
},
{
name: 'Second Chart',
label: 'c2',
data: [0.7, 0.5, 0.2, 0.4, 0.6, 0.1, 0.88, 0.35, 0.45],
backgroundColor: 'transparent',
borderColor: '#3cb44b',
borderWidth: 1,
pointBackgroundColor: '#3cb44b',
id: '1',
}
]
}
if (chLine) {
var myLineChart = new Chart(chLine, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
position: 'top',
labels: {
boxWidth: 5
}
},
events: ['click'],
onClick: clicked
}
});
}
function clicked(c, i, x) {
let getDataSetIndex = this.getElementAtEvent(c)[0]._datasetIndex;
console.log(chartData.datasets[getDataSetIndex].name)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<div class="container">
<div class="row my-3">
<div class="col">
<h4>Chart</h4>
</div>
</div>
<div class="row my-2">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<canvas id="chLine" height="100"></canvas>
</div>
</div>
</div>
</div>
</div>

Highcharts in Django using ajax

I am new to Django. I am making polls application and want to use highcharts to display graphs. I have a template which displays all the polls. I want to show the corresponding results of poll beside it in form of chart. Part of the template:
{% for question in poll_questions %}
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
{{question.question_text}}
{% for choice in question.poll_choices_set.all %}
<div>
<label><input type="radio" name="{{question.pk}}" value="{{ choice.pk }}">&nbsp {{choice.choice_text}}</label>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
<div id="{{ question.pk }}" class="chart" style="height: 400px; width: 400px"></div><br>
<script>
var question_id = '{{ question.pk }}'
</script>
<script src="{% static 'er_interface/polls.js' %}"></script>
</div>
{% endfor %}
Javascript file- polls.js:
$.getJSON('/er/poll/'+question_id ,function(data) {
$('#'+question_id).highcharts({
chart: {
type: 'pie'
},
title: {
text: question_id
},
tooltip: {
pointFormat: ':<b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
},
series: {
dataLabels: {
enabled: true,
formatter: function() {
return Math.round(this.percentage*100)/100 + ' %';
},
distance: 0,
}
}
},
series: data
});
});
The problem is that graph is shown just for the last poll question. Thanks
This is because in each of the for loops, question_id is overwritten. You might want to do something like this instead:
$('.chart').each(function() {
var that = this;
var question_id = $(this).attr('id');
$.getJSON('/er/poll/'+question_id ,function(data) {
$(that).highcharts({
...
That way, after rendering the page, you loop through each of the divs and render the appropriate chart.
Even better: use data-id="{{ book.id }}" and retrieve it with $(this).data('id') do avoid using the id attribute for something it's not really meant for.

Categories

Resources