Trouble with React: Making component equal to the result of a function - javascript

Created a Sandbox where you could see full code:
codesandbox.io/s/elastic-cray-mdpfx?file=/src/visualizations.js
So I first created three React hooks as follows and have already set their state in another function.
var [questionsAndAnswersGuide, setQuestionsAndAnswersGuide] = useState({});
var [dataForChart, setDataForChart] = useState({});
var [currentQuestionID, setCurrentQuestionID] = useState('Q1');
And then I created a function called generateChartData with this function signature
const generateChartData = (questionID, data, questionsAndAnswers) => {
var answersToFrequency = {};
var chartLabels = [];
var graphData = [];
var graphLabel = "Answers";
var graphBackgroundColors = [
'rgba(7,221,100,0.6)',
'rgba(63,130,7, 0.6)',
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162 ,235, 0.6)',
'rgba(200,7,100)',
'rgba(255,206,86,0.6)',
'rgba(75,192,192,0.6)',
'rgba(153,102,255,0.6)',
'rgba(255,159,64,0.6)',
'rgba(255,99,132,0.6)'
];
for(var i = 0; i < questionsAndAnswers[questionID].length; i++) {
answersToFrequency[questionsAndAnswers[questionID][i]] = 0;
}
for(const post of data) {
if(post[questionID] != "") {
answersToFrequency[post[questionID]] += 1;
}
}
for(var key in answersToFrequency) {
if(!isNaN(answersToFrequency[key])) {
chartLabels.push(key);
graphData.push(answersToFrequency[key]);
}
}
return {labels: chartLabels, datasets: [{label: graphLabel, data:
graphData, backgroundColor: graphBackgroundColors}]};
}
And this function returns a dictionary that contains data
Now I created a Chart class that would just display a bar graph.
class Chart extends Component {
constructor(props) {
super(props);
this.state = {
chartData: props.chartData
}
}
static defaultProps = {
displayTitle:true,
displayLegend:true,
legendPosition:'right',
questionNumber: 'Question 1'
}
render() {
return (
<div className='chart'>
<Bar
data={this.state.chartData}
options={{
title: {
display: this.props.displayTitle,
text: 'Bar Chart for ' + this.props.questionNumber,
fontSize:50
},
legend: {
display: this.props.displayLegend,
position: this.props.legendPosition
}
}}
/>
</div>
)
}
}
export default Chart;
However, when I say that the chartData should be the result of the function generateChartData, it fails to actually hold the value of the result of generateChartData and in the Chart class, it says that the value of chartData is undefined. How do I properly make chartData equal to the result of function generateChartData?
useEffect(() => { <br>
chart(); <br>
}, []); <br>
return ( <br>
<div className='Visualization'> <br>
<Chart chartData={generateChartData(currentQuestionID, dataForChart, questionsAndAnswersGuide)}
legendPosition='bottom'/>
However when I do something like this:
useEffect(() => { <br>
chart(); <br>
}, []); <br>
return ( <br>
<div className='Visualization'> <br>
<Chart chartData={{labels: ['Miami', 'San Francisco', 'Chicago', 'New York', 'Los Angeles', 'Houston'],
datasets: [
{
label: 'Population',
data: [
104343,
423424,
902114,
1000533,
156789,
78939
],
backgroundColor: [
'rgba(7,221,100,0.6)',
'rgba(63,130,7, 0.6)',
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162 ,235, 0.6)',
'rgba(200,7,100)',
'rgba(255,206,86,0.6)',
'rgba(75,192,192,0.6)',
'rgba(153,102,255,0.6)',
'rgba(255,159,64,0.6)',
'rgba(255,99,132,0.6)'
]
}
]
}
} legendPosition='bottom'/>
It generates the chart for me ad Im not sure where I am going wrong here. Moreover, if I now try this:
const generateChartData = (questionID, data, questionsAndAnswers) => {
var answersToFrequency = {};
var chartLabels = [];
var graphData = [];
var graphLabel = "Answers";
var graphBackgroundColors = [
'rgba(7,221,100,0.6)',
'rgba(63,130,7, 0.6)',
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162 ,235, 0.6)',
'rgba(200,7,100)',
'rgba(255,206,86,0.6)',
'rgba(75,192,192,0.6)',
'rgba(153,102,255,0.6)',
'rgba(255,159,64,0.6)',
'rgba(255,99,132,0.6)'
];
for(var i = 0; i < questionsAndAnswers[questionID].length; i++) {
answersToFrequency[questionsAndAnswers[questionID][i]] = 0;
}
for(const post of data) {
if(post[questionID] != "") {
answersToFrequency[post[questionID]] += 1;
}
}
for(var key in answersToFrequency) {
if(!isNaN(answersToFrequency[key])) {
chartLabels.push(key);
graphData.push(answersToFrequency[key]);
}
}
return {labels: ['Miami', 'San Francisco', 'Chicago', 'New York', 'Los Angeles', 'Houston'],
datasets: [
{
label: 'Population',
data: [
104343,
423424,
902114,
1000533,
156789,
78939
],
backgroundColor: [
'rgba(7,221,100,0.6)',
'rgba(63,130,7, 0.6)',
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162 ,235, 0.6)',
'rgba(200,7,100)',
'rgba(255,206,86,0.6)',
'rgba(75,192,192,0.6)',
'rgba(153,102,255,0.6)',
'rgba(255,159,64,0.6)',
'rgba(255,99,132,0.6)'
]
}
]
}
`` }
It fails to actually hold the value of the result of generateChartData and in the Chart class, it says that the value of chartData is undefined.

Related

chart.js labels Left to Right

i want to invert labels from Left to Right.
what do i have?
a JSON File in which the data is coming from Google Sheet's App Script.
i Have Created a chart with the help of this JSON file and Chart.js
in this chart the Levels which is time is printed right to left.
What Do i need?
i want to print the levels from Left to Right.
Google Sheet App Script Code
labels Left to Rightfunction doGet(e) {
var sheet = SpreadsheetApp.getActive();
var nse = sheet.getSheetByName("Sheet3");
var data = [];
var rlen = nse.getLastRow();
var clen = nse.getLastColumn();
var rows = nse.getRange(1, 1, rlen, clen).getDisplayValues(); // Modified
for (var i = 1; i < rows.length; i++) {
var datarow = rows[i];
var record = {};
for (var j = 0; j < clen; j++) {
record[rows[0][j]] = datarow[j];
}
data.push(record);
}
var result = JSON.stringify(data);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}
<div style="overflow: scroll;">
<canvas width="900" height="400" id="myChart"></canvas>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
<script>
// setup
const data = {
labels: [],
datasets: [{
label: 'Nifty_PCR_COI',
data: [],
backgroundColor: [
'rgba(255, 26, 104, 0.2)'
],
borderColor: [
'rgba(255, 26, 104, 1)'
],
tension: 0.4,
},{
label: 'Bank_Nifty_PCR_COI',
data: [],
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(54, 162, 235, 1)'
],
tension: 0.4,
}]
};
// config
const config = {
type: 'line',
data,
options: {
animation: false,
responsive: false,
scales: {
y: {
beginAtZero: true,
position: 'right'
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
//Json Fetch
getData();
async function getData() {
const response = await fetch(
'https://script.googleusercontent.com/macros/echo?user_content_key=r9CiwwP04Rh83CglKNwLbJw3zKlvAIWVj4Yf9a5cT3CPRmlxaBB9bOAMnkFV2os4ee10iaj9S7HNOU5axJWhdXmuYbHPVyWnm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnC4mxGG_R4juVl897H-HHcU5jBSu36oRyKZzBJteCuzXZ2p8eeHkRfjTV-mrMKhBOgim2y6bAoCZpSiZg9-Rh7EUjhE06fNngtz9Jw9Md8uu&lib=MQ0aMrcKwzFLX_7mD1gjcTxV-kV6j6m2N');
const jsondata = await response.json();
length = jsondata.length;
labels = [];
Nifty_PCR_COI = [];
Bank_Nifty_PCR_COI = [];
for (i = 0; i < length; i++) {
labels.push(jsondata[i].TimeCOI);
Nifty_PCR_COI.push(jsondata[i].Nifty_PCR_COI);
Bank_Nifty_PCR_COI.push(jsondata[i].Bank_Nifty_PCR_COI);
myChart.config.data.labels = labels;
myChart.config.data.datasets[0].data = Nifty_PCR_COI;
myChart.config.data.datasets[1].data = Bank_Nifty_PCR_COI;
myChart.update();
}
}
setInterval(getData, 5000)
</script>

Use an array as chart values

I need an array with chart values, I obtained one but after exiting from the function it became blank, here's what happens: Example
function AddvotoTec(votor) {
class Avg {
constructor() {}
static average(votor) {
var total = 0;
var count = 0;
jQuery.each(votor, function(index, value) {
total += value;
count++;
});
return total / count;
}
}
var mvoti = Avg.average(votor);
var mvoti = Math.round((mvoti + Number.EPSILON) * 10) / 10;
const myJSON = JSON.stringify(mvoti);
voti(myJSON);
}
var allvoti = [];
function voti(Voti) {
allvoti.push(Voti);
}
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: [
'rgb(255, 132, 0)'
],
borderColor: 'rgb(255, 99, 132)',
data: allvoti,
}]
};
The chart that I used is Chart.js.

vue-chartjs not updating on array.push()

I'm using vue-chartjs to show a line chart on my website. When I click on a button it's supposed to add another value to the chart. The dataset is updated but the chart is not.
LinieChart.vue
<script>
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
export default {
extends: Line,
mixins: [reactiveProp],
props: {
options: {
type: Object,
default: null
}
},
mounted () {
this.renderChart(this.chartData, this.options)
},
methods: {
}
}
</script>
I added this to my dashboard.vue
Where the chart is displayed
<line-chart
ref="LineChart"
:chart-data="chartdata"
:options="options"
class="h-64"
/>
The JavaScript:
<script>
export default {
middleware: 'auth',
layout: 'dashboard',
name: 'Dashboard',
components: {
temporaryDisableModal,
LineChart
},
data: () => ({
sensors: [],
sensorTypes: [],
valueTypes: [],
measurements: [],
websockets: [],
lastMeasurements: null,
loaded: false,
chartdata: null,
options: {
maintainAspectRatio: false,
responsive: true
}
}),
beforeMount () {
},
async mounted () {
this.fillData()
const self = this
// self.fillData()
await self.getSensors()
self.loaded = false
self.loaded = true
console.log('Sensors:')
console.log(self.sensors)
console.log(self.sensors.length)
for (let i = 0; i < self.sensors.length; i++) {
console.log(i)
console.log('Subscribed to ' + self.sensors[i].id)
self.measurements[self.sensors[i].id] = []
console.log(self.measurements)
window.Echo.channel('measurement.' + self.sensors[i].id).listen('.App\\Events\\WebsocketMeasurements', (e) => {
console.log('Data:')
console.log(e)
self.websockets.push(e.measurement)
self.measurements[self.sensors[i].id].push(e.measurement)
console.log(self.measurements)
})
}
},
methods: {
log () {
this.chartdata.labels.push(10)
this.chartdata.datasets[0].data.push(10)
this.chartdata.datasets[1].data.push(10)
},
fillData () {
this.chartdata = {
labels: this.getRandomInt(),
datasets: [
{
label: 'value_1',
borderColor: 'rgba(131, 24, 48, 1)',
backgroundColor: 'rgba(131, 24, 48, 0.3)',
data: this.getRandomInt()
},
{
label: 'value_2',
borderColor: 'rgba(216, 42, 81, 1)',
backgroundColor: 'rgba(216, 42, 81, 0.3)',
data: this.getRandomInt()
}
]
}
},
getRandomInt () {
let array = []
for (let i = 0; i < 100; i++) {
array.push(Math.floor(Math.random() * (6) * Math.random() * 3 * Math.random() * 9) + 15)
}
console.log(array)
return array
},
// other functions...
</script>
So when I execute the function log() it should add the value 10 as label and a dot in the line. It is added to the dataset, just not to the chart.
When I executed the log() function i get an error when hovering the chart:
Chart.js?30ef:6719 Uncaught TypeError: Cannot read property 'skip' of undefined
This does not happen when I haven't executed the function yet.
This is a known problem with vuecharts, instead of modifying nested elements on data reassign them all along, so instead of this:
this.chartdata.labels.push(10)
this.chartdata.datasets[0].data.push(10)
this.chartdata.datasets[1].data.push(10)
Do this:
this.chartdata.labels = MyNewArrayOfLabels
this.chartdata.datasets= [ //Me new array of datasets
{
label: 'value_1',
borderColor: 'rgba(131, 24, 48, 1)',
backgroundColor: 'rgba(131, 24, 48, 0.3)',
data: this.getRandomInt()
},
{
label: 'value_2',
borderColor: 'rgba(216, 42, 81, 1)',
backgroundColor: 'rgba(216, 42, 81, 0.3)',
data: this.getRandomInt()
}
]

Can anyone help me move data from an Axios JSON response to a plot points on a Chart js line chart?

I am working on building a React app that contains a line chart representing the timeline of data recordings from a certain point in time to present day. I am using the JS library Chart js. Specifically the 'react-chartjs-2' plugin. I am using the '/historical/all' path of the following API:
[https://corona.lmao.ninja/docs/?urls.primaryName=version%202.0.0#/][1]
I am successfully retrieving a response from the Axios GET request. But the structuring of the JSON being sent back to me is confusing me when it comes to the implementation I have been following to build the application. I have a lot of the scaffolding in place, but I am struggling to get the data from GET request function to the line chart.
The data is being sent in the following structure:
{
"cases": {
"3/21/20": 304507,
"3/22/20": 336953,
"3/23/20": 378231,
"3/24/20": 418041,
"3/25/20": 467653,
"3/26/20": 529591,
"3/27/20": 593291,
"3/28/20": 660693,
"3/29/20": 720140,
"3/30/20": 782389,
"3/31/20": 857487,
"4/1/20": 932605,
"4/2/20": 1013466,
"4/3/20": 1095917,
"4/4/20": 1176060,
"4/5/20": 1249754,
"4/6/20": 1321481,
"4/7/20": 1396476,
"4/8/20": 1480202,
"4/9/20": 1565278,
"4/10/20": 1657526,
"4/11/20": 1735650,
"4/12/20": 1834721,
"4/13/20": 1904838,
"4/14/20": 1976191,
"4/15/20": 2056054,
"4/16/20": 2152437,
"4/17/20": 2240190,
"4/18/20": 2317758,
"4/19/20": 2401378
},
"deaths": {
"3/21/20": 12973,
"3/22/20": 14651,
"3/23/20": 16505,
"3/24/20": 18625,
"3/25/20": 21181,
"3/26/20": 23970,
"3/27/20": 27198,
"3/28/20": 30652,
"3/29/20": 33925,
"3/30/20": 37582,
"3/31/20": 42107,
"4/1/20": 47180,
"4/2/20": 52983,
"4/3/20": 58787,
"4/4/20": 64606,
"4/5/20": 69374,
"4/6/20": 74565,
"4/7/20": 81937,
"4/8/20": 88338,
"4/9/20": 95521,
"4/10/20": 102525,
"4/11/20": 108502,
"4/12/20": 114090,
"4/13/20": 119481,
"4/14/20": 125983,
"4/15/20": 134176,
"4/16/20": 143800,
"4/17/20": 153821,
"4/18/20": 159509,
"4/19/20": 165043
},
"recovered": {
"3/21/20": 91682,
"3/22/20": 97889,
"3/23/20": 98341,
"3/24/20": 107890,
"3/25/20": 113604,
"3/26/20": 121966,
"3/27/20": 130659,
"3/28/20": 138949,
"3/29/20": 148616,
"3/30/20": 164100,
"3/31/20": 176442,
"4/1/20": 191853,
"4/2/20": 208528,
"4/3/20": 223621,
"4/4/20": 243575,
"4/5/20": 257000,
"4/6/20": 273259,
"4/7/20": 296263,
"4/8/20": 324507,
"4/9/20": 348813,
"4/10/20": 370241,
"4/11/20": 395521,
"4/12/20": 414599,
"4/13/20": 440897,
"4/14/20": 466051,
"4/15/20": 502053,
"4/16/20": 532409,
"4/17/20": 557798,
"4/18/20": 581355,
"4/19/20": 612056
}
}
I would like for each category (cases, deaths, recovered) to represent a line on the chart showing the progression over time, but I'm unsure how to handle it. With the intention being that the dates would be the X-axis and the points would be plotted in a different colored line for each.
Would anyone be able to help with this at all? I would greatly appreciate some guidance. Below are the two primary files corresponding to the Chart and API handling:
index.js
export const fetchDailyData = async () => {
try {
const { data } = await axios.get(`${url}/historical/all`);
const labels = Object.keys(data.cases);
const cases = labels.map((name) => data.cases[name]);
const deaths = labels.map((name) => data.deaths[name]);
const recovered = labels.map((name) => data.recovered[name]);
return {labels, cases, deaths, recovered};
} catch (error) {
return error;
}
}
Chart.jsx
import React, { useState, useEffect } from 'react';
import { Line, Bar } from 'react-chartjs-2';
import { fetchDailyData } from '../../api';
import styles from './Chart.module.css';
const Chart = ({data: { labels, cases, deaths, recovered }}) => {
const [dailyData, setDailyData] = useState([]);
useEffect(() => {
const fetchAPI = async () => {
setDailyData(await fetchDailyData());
}
fetchAPI();
}, []);
const lineChart = (
<Line data = {
{
labels,
datasets: [{
data:cases,
label: 'Infected',
borderColor: '#3333ff',
fill: true,
}, {
data: deaths,
label: 'Deaths',
borderColor: 'red',
backgroundColor: 'rgba(255, 0, 0, 0.5)',
fill: true,
},
{
data: recovered,
label: 'Recovered',
borderColor: 'green',
backgroundColor: 'rgba(0, 255, 0, 0.5)',
fill: true,
}],
}
}
/>
);
return (
<div className = { styles.container }>
{lineChart}
</div>
);
};
export default Chart;
Here is a complete solution:
// Create the chartData state
const [chartData, setChartData] = useState();
// in your fetch function, convert the data to chartData
const labels = Object.keys(data.cases);
const cases = labels.map((name) => data.cases[name]);
const deaths = labels.map((name) => data.deaths[name]);
const recovered = labels.map((name) => data.recovered[name]);
setChartData({
labels,
datasets: [{
data: cases,
label: 'Infected',
borderColor: '#3333ff',
fill: true
}, {
data: deaths,
label: 'Deaths',
borderColor: 'red',
backgroundColor: 'rgba(255, 0, 0, 0.5)',
fill: true
}, {
data: recovered,
label: 'Recovered',
borderColor: 'green',
backgroundColor: 'rgba(0, 255, 0, 0.5)',
fill: true
}]
})
// Now render your chart (but make sure chartData exists)
return (
<div className = { styles.container }>
{chartData &&
<Line data={chartData} />
}
</div>
);
First extract the x labels:
const labels = Object.keys(dailyData.cases);
Then extract the y values for each serie:
const cases = Object.keys(dailyData.cases).map((name) => dailyData.cases[name]);
const deaths = Object.keys(dailyData.deaths).map((name) => dailyData.deaths[name]);
const recovered = Object.keys(dailyData.recovered).map((name) => dailyData.recovered[name]);
Then assemble everything into a chart js object:
<Line data = {
labels,
datasets: [{
data: cases,
label: 'Infected',
borderColor: '#3333ff',
fill: true
}, {
data: deaths,
label: 'Deaths',
borderColor: 'red',
backgroundColor: 'rgba(255, 0, 0, 0.5)',
fill: true
}, {
data: recovered,
label: 'Recovered',
borderColor: 'green',
backgroundColor: 'rgba(0, 255, 0, 0.5)',
fill: true
}]
}
/>

How to use JSON data in creating a chart with chartjs?

In my controller I have an Action method that will find all questions in a table called Questions, and the answers for each question.
This Action is of type ContentResult that will return a result serialized in Json format.
public ContentResult GetData()
{
var datalistQuestions = db.Questions.ToList();
List<PsychTestViewModel> questionlist = new List<PsychTestViewModel>();
List<PsychTestViewModel> questionanswerslist = new List<PsychTestViewModel>();
PsychTestViewModel ptvmodel = new PsychTestViewModel();
foreach (var question in datalistQuestions)
{
PsychTestViewModel ptvm = new PsychTestViewModel();
ptvm.QuestionID = question.QuestionID;
ptvm.Question = question.Question;
questionlist.Add(ptvm);
ViewBag.questionlist = questionlist;
var agree = //query
var somewhatAgree = //query
var disagree = //query
int Agree = agree.Count();
int SomewhatAgree = somewhatAgree.Count();
int Disagree = disagree.Count();
ptvmodel.countAgree = Agree;
ptvmodel.countSomewhatAgree = SomewhatAgree;
ptvmodel.countDisagree = Disagree;
questionanswerslist.Add(ptvmodel);
ViewBag.questionanswerslist = questionanswerslist;
}
return Content(JsonConvert.SerializeObject(ptvmodel), "application/json");
}
Now, my problem is the pie chart is not being created and I don't quite know how to push the values to my data structure?
What should I be doing instead?
Here is my script:
#section Scripts {
<script type="text/javascript">
var PieChartData = {
labels: [],
datasets: [
{
label: "Agree",
backgroundColor:"#f990a7",
borderWidth: 2,
data: []
},
{
label: "Somewhat Agree",
backgroundColor: "#aad2ed",
borderWidth: 2,
data: []
},
{
label: "Disgree",
backgroundColor: "#9966FF",
borderWidth: 2,
data: []
},
]
};
$.getJSON("/PsychTest/GetData/", function (data) {
for (var i = 0; i <= data.length - 1; i++) {
PieChartData.datasets[0].data.push(data[i].countAgree);
PieChartData.datasets[1].data.push(data[i].countSomewhatAgree);
PieChartData.datasets[2].data.push(data[i].countDisagree);
}
var ctx = document.getElementById("pie-chart").getContext("2d");
var myLineChart = new Chart(ctx,
{
type: 'pie',
data: PieChartData,
options:
{
responsive: true,
maintainaspectratio: true,
legend:
{
position : 'right'
}
}
});
});
</script>
You need two arrays for creating your chart. One of them indicates titles and another one shows the number of each titles. You have titles in the client side, so you only need the number of each options and it could be fetched from a simple server method like:
[HttpGet]
public JsonResult Chart()
{
var data = new int[] { 4, 2, 5 }; // fill it up whatever you want, but the number of items should be equal with your options
return JsonConvert.SerializeObject(data)
}
The client side code is here:
var aLabels = ["Agree","Somewhat Agree","Disagree"];
var aDatasets1 = [4,2,5]; //fetch these from the server
var dataT = {
labels: aLabels,
datasets: [{
label: "Test Data",
data: aDatasets1,
fill: false,
backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
borderWidth: 1
}]
};
var opt = {
responsive: true,
title: { display: true, text: 'TEST CHART' },
legend: { position: 'bottom' },
//scales: {
// xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }],
// yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }]
//}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: dataT,
options: opt
});
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.7.1/Chart.min.js"></script>
<div Style="font-family: Corbel; font-size: small ;text-align:center " class="row">
<div style="width:100%;height:100%">
<canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas>
</div>
</div>
If you are still looking to use json for chart.js charts.
Here is a solution which fetch a json file and render it on chart.js chart.
fetch('https://s3-us-west-2.amazonaws.com/s.cdpn.io/827672/CSVtoJSON.json')
.then(function(response) {
return response.json();
})
.then(function(ids) {
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ids.map(function(id) {
return id.Label;
}),
datasets: [
{
label: "value2",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value2;
}),
},
{
label: "value",
//backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ids.map(function(id) {
return id.Value;
}),
},
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Sample Json Data Chart'
}
}
});
});
see running code on jsfiddle here

Categories