I wanted to create a graph which contains a Time Cartesian axis. The docs tell me that I need to use an adapter for a type: 'time' axis. I chose chartjs-adapter-date-fns, and imported it using the following cdn:
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
Now the docs tell me an object must be passed as the adapters.date property of an axis id. But which class/object should I put there? I'm stuck here. Can anyone point me in the right direction?
I'm using ChartJS 3.4.1 and Chartisan.
x: {
adapters: {
date: {
// Adapter object here.
}
},
type: 'time',
time: {
unit: 'day'
},
},
Many thanks in advance!
The documentation for chartjs-adapter-date-fns states:
date-fns requires a date-fns locale object to be tagged on to each format() call, which requires the locale to be explicitly set via the adapters.date option
And gives the following example:
// import date-fns locale:
import {de} from 'date-fns/locale';
// scale options:
{
adapters: {
date: {
locale: de
}
}
}
Hopefully not too late, but just in case: I grappled with this, too, and in the end found that you can simply feed chartjs with time scale integers as x values. Convert your timestamps to seconds since the epoch and multiply by 1000, because js uses milliseconds whereas unix uses seconds.
My code is in python, so I convert the timestamp string to milliseconds since the epoch, fist:
# get data from backend
hist = self.backend_get(f"/{name}/history")
# convert format for chart, filter out None
data_l = [{'x' : 1000*int(datetime.fromisoformat(d['timestamp']).strftime('%s')),
'y' : d['value']} for d in hist if d['value'] is not None]
label = "<insert your label>"
Now construct the data
data = {
'type': 'line',
'data': {
'labels': [],
'datasets': [{
'label': label,
'data': data_l,
}]
},
'options': {
'scales': {
'x': {
'type': 'time',
'time': {'unit': 'day'},
},
},
},
}
Finally insert the charts js and canvas into the html:
html_s += '''
<div>
<canvas id="myChart" class="history_canvas"></canvas>
</div>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx,
'''
html_s += f'{data}'
html_s += '''
);
</script>
<h3>Raw data</h3>
'''
PS I think this only works in Unix because of the epoch.
Nevermind, just adding the cdn was sufficient. The problem was that the labels weren't in date format but in relative time instead ("2 hours ago" instead of 20-07-2021)
Related
I upgraded to the newest Chart.JS version 3.0.2. and I'm trying to get a time series chart to render. Here is my config:
{
type: 'line',
data: {
datasets: [{
data: dataForChart
}]
},
options: {
scales: {
x: {
type: 'time'
}
}
}
}
I have imported the module like this:
import ChartJS from 'chart.js/auto';
The error I'm getting is:
Error: This method is not implemented: either no adapter can be found or an incomplete integration was provided.
Any tips on what I could be making wrong?
Here is a code sandbox with that problem: https://codesandbox.io/s/throbbing-cdn-j6q2u?file=/src/App.js
You need to install and import an adapter, in your case it's moment adapter for time series
npm install moment chartjs-adapter-moment --save
then import it in your component:
import 'chartjs-adapter-moment';
for more info about adapters, check this
This answer comes a bit late but for everyone who stumbles here: You need a date adapter. Find a full list here
Once you installed i.e. date-fns via npm install date-fns chartjs-adapter-date-fns --save in your root directory you have to do two things to make it work in your React project:
Add this at the top of your file import 'chartjs-adapter-date-fns'; and import { enUS } from 'date-fns/locale';
Inside your options:
options = {
...
scales: {
x: {
type: 'time',
// add this:
adapters: {
date: {
locale: enUS,
},
},
}
},
...
}
You need an adaptor as stated above. Look here: https://github.com/chartjs/chartjs-adapter-date-fns#cdn
One option is to add the following cdn links:
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
As stated in your error and the documentation you need an adapter to convert the dates to date objects, see documentation: https://www.chartjs.org/docs/latest/axes/cartesian/time.html#date-adapters
I think you should put list in x like below code.
scales: {
x: [{
type: 'time'
}]
}
I am working on data visualization and want to show average wage and Estimated population on EVERY state of US. Now I am using google geochart for this part and I almost get the work done.
But I found out google geo chart doesn't support data which contains more than 3 columns.
Below is my work and how it looks when I run it.
function drawNewChart(){
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'my key'
});
google.charts.setOnLoadCallback(function(){
let map_data = [['State', 'Count', 'AvgWages']]
Object.getOwnPropertyNames(stateData).forEach(function(item, index){
map_data.push(['US-' + item, stateData[item].count, stateData[item].AvgWages / stateData[item].count])
})
console.log('full data', map_data)
var data = google.visualization.arrayToDataTable(map_data);
var options = {
region: "US",
resolution: "provinces"
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
With 3 columns it works fine and it shows this.
However I want to add 1 more column to it. (EstimatedPopulation). When I add this then it shows this error message:
Incompatible data table: Error: Table contains more columns than expected (Expecting 3 columns)
How can I solve this problem ?
Here are few solutions for your query
https://codesandbox.io/s/xjqrk659zw?file=/src/index.js:847-892
You need to define
tooltip: { isHtml: true, trigger: "visible" }
in the options
And then
{ role: "tooltip", type: "string", p: { html: true } }
in your data parameter.
Hope it will help
As i am pretty new to Charting libraries and in my case i have been asked to implement a Chartjs library for my requirement. So i have chosen a chartjs library.
The use case i must want to know if anybody can help me then it would be a great time saver for me. Actually i am googleling since morning for this.
The actual use case is i have doughnut chart in which i am trying to show the data of a single value. As i have gone through the documentation the chartjs works on a array of data values. But my API is having only one value, means in my case its a counter variable. Assume if my maximum counter limit is say 5000 then i have to show that 5000 as a maximum counter and as the current counter is say 100 then i have to show it in the doughnut arc in red color. Means how much the graph has consumed the data something like that.
Assume total runs 5000
If runs became any count like 100 then we need to do minus from total runs - current runs count = 4900 inside the doughnut circle. As the runs increases then we need to show the reduced count runs inside the doughnut circle graph.
Once if the current runs count comes to total runs the show the circle in red color and make the count to 0.
Is this possible using Chartjs? See below picture.
There is no built-in support for doing this in Chart.js, however, it can be achieved using a very simple hack. Look at the code and try to understand, if any issues feel free to comment.
I have used chartjs-datalabels plugin to show datalabels on the pieChart.
Hope it helps!
Fiddle -> http://jsfiddle.net/y6mnkz84/7/
function drawPieChart(value, maxValue) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Consumed"],
datasets: [{
data: [value, maxValue - value],
backgroundColor: ['green', 'red'],
}]
},
options: {
tooltips: {
enabled: false,
},
plugins: {
datalabels: {
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
display: function(context) {
var dataset = context.dataset;
var value = dataset.data[context.dataIndex];
return value > 0;
},
color: 'white'
}
}
}
});
}
drawPieChart(5000, 5000);
I'am writing an application for budget management and i am using angular-chart.js.
i want to use a dataset to override the initial data(mainly to add new data to the graph and give diffrent color for each bar,label etc.)and set label and colors according to the value of the data.
currently,i tried to do that hard coded but only the first value is being override.
here is the code i am using :
angular.module("app2", ["chart.js"]).controller("MixedChartCtrl",
function($scope) {
$scope.colors = ['#45b7cd', '#ff6384', '#ff8e72'];
$scope.labels = ['', ''];
$scope.data = [65, 11];
$scope.datasetOverride = [
{
label: 'Override Series A',
borderWidth: 1,
type: 'bar',
data: [345]
},
{
label: "Bar chart1",
borderWidth: 1,
type: 'bar',
data: [45]
}
];
});
Hoping that yourquestion is, you want a fill color/label/something to each individual data (for each bar).
Above (your) code snippet is used when you have two data sets.
All these dataset properties will accept String when the same property value has to set for all data, and they will also accept Array[String] - when you want to set different property values for different data in the same dataset. (like below).
$scope.data = [65,11];
$scope.datasetOverride = [
{
label: ['something', 'otherthing'],
borderWidth: [1,2],
backgroundColor: ['#FF4242','#2291ff']
}
]
so now I understood that you might be adding dynamically data.
so you have to push data into DATASET something like this:
$scope.data.push(345);
So if you want to set different properties for these you need to push the properties (arrays).
$scope.datasetOverride[0][label].push('someother thing');
$scope.datasetOverride[0][borderWidth].push(2);
$scope.datesetOverride[0][backgroundColor].push('#46bfb8');
This will add a bar with new color/label/etc beside the previous bars.
I hope I understood your question and this will help.
This hopefully is an easy questions.
I'm using Highcharts through chartit in Django and can get most of my graphs to work (temp and time). I'm now trying to graph the values ON and OFF over time. It seems that highcharts can't interpret the strings in the Y Axis (ON and OFF). Is there a way to get it to use those values?
I've tried using something like this in the chart_option section.
'yAxis': {
'categories': ['ON', 'OFF'],
'title': {'text': 'Status'}}
Many thanks!
Point's y coordinate in series' data must be a number, so you would have to process your data to have it in required format. It would be for the best to do this server side and provide proper data for JS, but if that is not possible then you could process data in JS.
$(function() {
var data = ['ON', 'OFF', 'OFF', 'ON'],
processedData = [];
Highcharts.each(data, function(point) {
processedData.push(point === 'ON' ? 1 : 0);
});
$('#container').highcharts({
'yAxis': {
'categories': ['ON', 'OFF'],
'title': {
'text': 'Status'
}
},
series: [{
data: processedData
}]
});
});
Example: http://jsfiddle.net/ptu6qhjy/