Trying to put a 3rd axis to the chart...,
the object data is beeing received, but not displayed. What is wrong ?
I checked that the data is pushed , but it is not displayed.
I have no idea , why data is not in the chart,
the spelling should be ok.
If pushing data from IOT,
I always get 3 Objects with data,
as shown in the Picture.
/* eslint-disable max-classes-per-file */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-undef */
$(document).ready(() => {
// if deployed to a site supporting SSL, use wss://
const protocol = document.location.protocol.startsWith('https') ? 'wss://' : 'ws://';
const webSocket = new WebSocket(protocol + location.host);
// A class for holding the last N points of telemetry for a device
class DeviceData {
constructor(deviceId) {
this.deviceId = deviceId;
this.maxLen = 50;
this.timeData = new Array(this.maxLen);
this.temperatureData = new Array(this.maxLen);
this.PrsInData =new Array(this.maxLen);
this.PrsOutData =new Array(this.maxLen);
}
addData(time,Temperature, PrsIn,PrsOut) {
this.timeData.push(time);
this.temperatureData.push(Temperature);
this.PrsInData.push(PrsIn);
this.PrsOutData.push(PrsOut);
if (this.timeData.length > this.maxLen) {
this.timeData.shift();
this.temperatureData.shift();
this.PrsOutData.shift();
this.PrsInData.shift();
}
}
}
// All the devices in the list (those that have been sending telemetry)
class TrackedDevices {
constructor() {
this.devices = [];
}
// Find a device based on its Id
findDevice(deviceId) {
for (let i = 0; i < this.devices.length; ++i) {
if (this.devices[i].deviceId === deviceId) {
return this.devices[i];
}
}
return undefined;
}
getDevicesCount() {
return this.devices.length;
}
}
const trackedDevices = new TrackedDevices();
// Define the chart axes
const chartData = {
datasets: [
{
fill: false,
label: 'Temperature',
yAxisID: 'Temperature',
borderColor: 'rgba(255, 204, 0, 1)',
pointBoarderColor: 'rgba(255, 204, 0, 1)',
backgroundColor: 'rgba(255, 204, 0, 0.4)',
pointHoverBackgroundColor: 'rgba(255, 204, 0, 1)',
pointHoverBorderColor: 'rgba(255, 204, 0, 1)',
spanGaps: true,
},
{
fill: false,
label: 'PrsIn',
yAxisID: 'PrsIn',
borderColor: 'rgba(24, 120, 240, 1)',
pointBoarderColor: 'rgba(24, 120, 240, 1)',
backgroundColor: 'rgba(24, 120, 240, 0.4)',
pointHoverBackgroundColor: 'rgba(24, 120, 240, 1)',
pointHoverBorderColor: 'rgba(24, 120, 240, 1)',
spanGaps: true,
},
{
fill: false,
label: 'PrsOut',
yAxisID: 'PrsOut',
borderColor: 'rgba(24, 24, 240, 1)',
pointBoarderColor: 'rgba(24, 24, 240, 1)',
backgroundColor: 'rgba(24, 24, 240, 0.4)',
pointHoverBackgroundColor: 'rgba(24, 24, 240, 1)',
pointHoverBorderColor: 'rgba(24, 24, 240, 1)',
spanGaps: true,
}
]
};
const chartOptions = {
scales: {
yAxes: [{
id: 'Temperature',
type: 'linear',
scaleLabel: {
labelString: 'Temperature (ºC)',
display: true,
},
position: 'left',
ticks: {
max: 420,
min: 0
}
},
{
id: 'PrsIn',
type: 'linear',
scaleLabel: {
labelString: 'PrsIn',
display: true,
},
position: 'right',
}
,
{
id: 'PrsOut',
type: 'linear',
scaleLabel: {
labelString: 'PrsOut',
display: true,
},
position: 'right',
} ]
}
};
// Get the context of the canvas element we want to select
const ctx = document.getElementById('iotChart').getContext('2d');
const myLineChart = new Chart(
ctx,
{
type: 'line',
data: chartData,
options: chartOptions,
});
// Manage a list of devices in the UI, and update which device data the chart is showing
// based on selection
let needsAutoSelect = true;
const deviceCount = document.getElementById('deviceCount');
const listOfDevices = document.getElementById('listOfDevices');
function OnSelectionChange() {
const device = trackedDevices.findDevice(listOfDevices[listOfDevices.selectedIndex].text);
chartData.labels = device.timeData;
chartData.datasets[0].data = device.Temperature;
chartData.datasets[1].data = device.PrsInData;
chartData.datasets[2].data = device.PrsOutData;
myLineChart.update();
}
listOfDevices.addEventListener('change', OnSelectionChange, false);
// When a web socket message arrives:
// 1. Unpack it
// 2. Validate it has date/time and temperature
// 3. Find or create a cached device to hold the telemetry data
// 4. Append the telemetry data
// 5. Update the chart UI
webSocket.onmessage = function onMessage(message) {
try {
const messageData = JSON.parse(message.data);
console.log(messageData);
// time and either temperature or humidity are required
if (!messageData.MessageDate || (!messageData.IotData.Temperature && !messageData.IotData.PrsIn && !messageData.IotData.PrsOut )) {
return;
}
// find or add device to list of tracked devices
const existingDeviceData = trackedDevices.findDevice(messageData.DeviceId);
if (existingDeviceData) {
existingDeviceData.addData(messageData.MessageDate, messageData.IotData.Temperature, messageData.IotData.PrsIn, messageData.IotData.PrsOut);
} else {
const newDeviceData = new DeviceData(messageData.DeviceId);
trackedDevices.devices.push(newDeviceData);
const numDevices = trackedDevices.getDevicesCount();
deviceCount.innerText = numDevices === 1 ? `${numDevices} device` : `${numDevices} devices`;
newDeviceData.addData(messageData.MessageDate, messageData.IotData.Temperature, messageData.IotData.PrsIn, messageData.IotData.PrsOut);
// add device to the UI list
const node = document.createElement('option');
const nodeText = document.createTextNode(messageData.DeviceId);
node.appendChild(nodeText);
listOfDevices.appendChild(node);
// if this is the first device being discovered, auto-select it
if (needsAutoSelect) {
needsAutoSelect = false;
listOfDevices.selectedIndex = 0;
OnSelectionChange();
}
}
myLineChart.update();
} catch (err) {
console.error(err);
}
};
});
Temperature is missing in the chart
Related
I am trying to get messages from a websocket. If I place my javascript code inside the .cshtml file the onopen and onmessage events fire correctly. If I place the same code inside a separate javascript file and include it in the page file onopen fires correctly but onmessage never fires.
Code in cshtml file:
<script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
<script src="~/js/klines-graph.js"></script>
<script>
var klines = new Klines('#Model.Symbol', '5m');
klines.createKlines();
</script>
Code in javascript file:
class Klines {
constructor(symbol, interval) {
this.symbol = symbol;
this.interval = interval;
this.currentPrice = 0;
this.sum = 0;
this.onPriceChange = new Event('onPriceChange');
this.liveKlineSocket = new WebSocket('wss://stream.binance.com:9443/ws/' + symbol + '##kline_5m');
const chart = LightweightCharts.createChart(document.getElementById("chart"), {
width: 800,
height: 400,
layout: {
backgroundColor: '#ffffff',
textColor: 'rgba(0, 0, 0, 0.9)',
},
grid: {
vertLines: {
color: 'rgba(0, 0, 0, 0.9)',
},
horzLines: {
color: 'rgba(0, 0, 0, 0.9)',
},
},
crosshair: {
mode: LightweightCharts.CrosshairMode.Normal,
},
//localization: {
// priceFormatter: price => {
// return parseFloat(price).toFixed(10);
// },
//},
timeScale: {
borderColor: 'rgba(0, 0, 0, 0.8)',
timeVisible: true,
secondsVisible: false,
},
});
this.candleSeries = chart.addCandlestickSeries(
//{
// candle customization
// upColor: 'rgba(255, 144, 0, 1)',
// downColor: '#000',
// borderDownColor: 'rgba(255, 144, 0, 1)',
// borderUpColor: 'rgba(255, 144, 0, 1)',
// wickDownColor: 'rgba(255, 144, 0, 1)',
// wickUpColor: 'rgba(255, 144, 0, 1)',
//}
);
}
createKlines() {
fetch(`https://api.binance.com/api/v3/klines?symbol=${this.symbol}&interval=${this.interval}`)
.then(response => response.json())
.then(klineData => {
let candleStickList = klineData.map(item => {
return {
"time": item[0] / 1000,
"open": item[1],
"high": item[2],
"low": item[3],
"close": item[4]
};
});
this.candleSeries.setData(candleStickList);
this.currentPrice = candleStickList[candleStickList.length - 1].close;
this.liveKlineSocket.addEventListener('open', function (event) {
console.log('Connected to kline websocket');
});
this.liveKlineSocket.addEventListener('message', function (event) {
console.log('message');
let candleStick = JSON.parse(event.data);
this.candleSeries.update({
time: candleStick.openTime / 1000,
open: candleStick.open,
high: candleStick.high,
low: candleStick.low,
close: candleStick.close
});
});
}).catch(er => {
console.log(er);
});
}
}
I am starting to learn the chart.js library.
I drew a pie chart (like "pie"). When you hover over the slices of the diagram, a number appears in the pop-up window that sets the size of the sector.
new chart(
document.getElementById('diagram_1').getContext('2d'), {
type: 'pie',
data: {
labels: [
'Завершенная задача',
'Новая задача',
'Ошибка выполнения'
],
datasets: [{
label: '# of Votes',
data: [#successful_tasks, #new_tasks, #error_tasks],
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
responsive: false
}
}
)
How can you make this number still displayed at the top, where the sectors are listed (I marked this place with a red circle in the picture)?
I can add the required number to the labels array
...
data: {
labels: [
'Завершенная задача: ' + #successful_tasks,
'Новая задача: ' + #new_tasks,
'Ошибка выполнения: ' + #error_tasks
],
...
But then this number will appear twice in the tooltip
You can use the plugin system for this:
var options = {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
customNumber: {
textColor: 'red',
xOffset: 10,
yOffset: 0,
font: '24px Comic Sans MS'
}
}
},
plugins: [{
id: 'customNumber',
afterDraw: (chart, args, opts) => {
const hoveredSlice = chart._active[0];
const {
ctx,
chartArea: {
right
}
} = chart;
if (!hoveredSlice) {
return;
}
ctx.font = opts.font || '24px verdana, sans-serif'
ctx.fillStyle = opts.textColor || 'black'
const val = chart.data.datasets[hoveredSlice.datasetIndex].data[hoveredSlice.index];
const meassures = ctx.measureText(val);
const height = ctx.measureText('M').width;
ctx.fillText(val, (right - meassures.width - (opts.xOffset || 0)), height + (opts.yOffset || 0))
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
I found the answer. My project is written in CoffeeScript, but I think it would be more useful for the StackOverflow community to post the code in JS.
options: {
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc && arc.custom || {};
var getValueAtIndexOrDefault = Chart.helpers.getValueAtIndexOrDefault;
var arcOpts = chart.options.elements.arc;
var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
var value = chart.config.data.datasets[arc._datasetIndex].data[arc._index];
return {
text: label + ": " + value,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
index: i
};
});
} else {
return [];
}
}
}
}
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"
integrity="sha256-R4pqcOYV8lt7snxMQO/HSbVCFRPMdrhAFMH+vr9giYI=" crossorigin="anonymous"></script>
<div class="chart" style="position: relative; height:50vh; width:100%;margin: 0 auto;;">
<canvas id="myChart" width="400" height="400"></canvas></div>
<select id="date-choose">
<option value="Today">Today</option>
<option value="Yesterday">Yesterday</option>
<option value="7 Days">Last 7 Days</option>
</select>
<script>
function BuildChart(labels, values, chartTitle) {
var data = {
labels: labels,
datasets: [{
label: chartTitle, // Name the series
data: values,
backgroundColor: [
'rgba(50, 99, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)'
],
borderColor: [
'rgba(50, 90, 231, 1)',
'rgba(54, 162, 235, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)'
],
borderWidth: 1
}],
};
Chart.defaults.global.defaultFontColor = '#151515';
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
responsive: true, // Instruct chart js to respond nicely.
maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: ''
}
}],
yAxes: [{
ticks: {
callback: function(value, index, values) {
if (Math.floor(value) === value) {
return value;
}
}
}
}]
},
}
});
//$('#legend').html(myChart.generateLegend());
return myChart;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
console.log(json);
// Map json labels back to values array
var labels = json.feed.entry.map(function (e) {
return e.gsx$date.$t;
});
// Map json values back to values array
var values = json.feed.entry.map(function (e) {
return e.gsx$followers.$t;
});
for (i = 0; i < values.length; i++) {
if (values[i].charAt(0) == '-') {
values.length = values.length - 1;
labels.length = labels.length - 1;
} else if (values[i].charAt(0) == '+'){
values.length = values.length - 1;
labels.length = labels.length - 1;
}
}
for (i = 0; i < values.length; i++) {
values[i]= values[i].replace(/,/g, '');
}
BuildChart(labels.reverse(), values.reverse(), "Followers");
}
};
xhttp.open("GET", "https://spreadsheets.google.com/feeds/list/1nLLfOhAD6PGcIPc5mttyBFi1maoveEYpsz4MiU7JNAA/od6/public/full?alt=json", false);
xhttp.send();
</script>
I am using this chart to show the follower data of a certain person, I would like to have a dropdown in which the person can choose the interval they prefer to see or a dropdown with "yesterday", "last 3 days", "last 7 days" . Thanks in advance to those who take the trouble to help me. Is it possible to do something similar?
Thanks in advance
You can do that by changing the chart.config.options.scales.xAxes[0].ticks.max and chart.config.options.scales.xAxes[0].ticks.min values.
The code is above just note one thing: I noticed that the labels are in reverse time. The "today" date is on the right and the values on the left are days in the future.
I don't understand very well how you are trying to present the data but in any case that doesn't change the way how it is done. In the snippet above there is an example with an numeric input that adds a certain amount of days to the current date. So you would only need to translate that into your <select>.
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js" integrity="sha256-R4pqcOYV8lt7snxMQO/HSbVCFRPMdrhAFMH+vr9giYI=" crossorigin="anonymous"></script>
<div class="chart" style="position: relative; height:50vh; width:100%;margin: 0 auto;;">
<canvas id="myChart" width="400" height="400"></canvas></div>
Days from now: <input id="days" value="0" type="number" />
<br/>
<select id="date-choose" disabled>
<option value="1">Today</option>
<option value="2">Yesterday</option>
<option value="7">Last 7 Days</option>
</select>
<script>
let chart; // 1
let inp = document.getElementById("days");
inp.oninput = function() { // 3
const today = new Date().getTime() + +inp.value * 1000 * 60 * 60 * 24; // 4
const newMax = new Date(today).toISOString().split("T")[0]
console.log("newMax", newMax)
chart.config.options.scales.xAxes[0].ticks.max = newMax
chart.update();
};
function BuildChart(labels, values, chartTitle) {
var data = {
labels: labels,
datasets: [{
label: chartTitle, // Name the series
data: values,
backgroundColor: [
'rgba(50, 99, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)',
'rgba(50, 90, 231, 0.2)'
],
borderColor: [
'rgba(50, 90, 231, 1)',
'rgba(54, 162, 235, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)',
'rgba(50, 90, 231, 1)'
],
borderWidth: 1
}],
};
Chart.defaults.global.defaultFontColor = '#151515';
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
responsive: true, // Instruct chart js to respond nicely.
maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: ''
},
}],
yAxes: [{
ticks: {
callback: function(value, index, values) {
if (Math.floor(value) === value) {
return value;
}
}
}
}]
},
}
});
return myChart;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
//console.log(json);
// Map json labels back to values array
var labels = json.feed.entry.map(function(e) {
return e.gsx$date.$t;
});
// Map json values back to values array
var values = json.feed.entry.map(function(e) {
return e.gsx$followers.$t;
});
for (i = 0; i < values.length; i++) {
if (values[i].charAt(0) == '-') {
values.length = values.length - 1;
labels.length = labels.length - 1;
} else if (values[i].charAt(0) == '+') {
values.length = values.length - 1;
labels.length = labels.length - 1;
}
}
for (i = 0; i < values.length; i++) {
values[i] = values[i].replace(/,/g, '');
}
chart = BuildChart(labels.reverse(), values.reverse(), "Followers"); // 2
}
};
xhttp.open("GET", "https://spreadsheets.google.com/feeds/list/1nLLfOhAD6PGcIPc5mttyBFi1maoveEYpsz4MiU7JNAA/od6/public/full?alt=json", false);
xhttp.send();
</script>
There are few important points from the code above (search for the comment to reference the number). These are:
chart is created so that it holds the chart instance
BuildChart output is saved into chart
A new oninput listener needs to be created to respond to date changes. If you use a <select> you can use the onchange event instead.
Here the calculation is made by substracting the amount of days we want to show.
I am populating my bar chart with very simple data. But it seems that it stays always left with little width no matter what I do. How can I solve this can you pls tell me?I also tried with bar thickness and bar percentage doesn't seem to change any thing. Is there anything I can do? Thank you.
Js part:
var labels = ["Request for Information", "Product Availability", "Offer Eligibility", "Price Query", "How To Order",
"Delivery Duration", "Offer Duration", "Product Feature Query", "Delivery Charge", "Order Confirmation"]
var barData=[17076, 16313, 11337, 11000, 6116, 5957, 5590, 4815, 3825, 335]
var tempbackgroundColor=['rgba(192, 57, 43, 1)',
'rgba(155, 89, 182, 1)',
'rgba(84, 153, 199, 1)',
'rgba(69, 179, 157, 1)',
'rgba(245, 176, 65 , 1)',
'rgba(236, 240, 241, 1)',
'rgba(127, 140, 141, 1)',
'rgba(44, 62, 80, 1)'
]
var dataSets = [];
for (var i = 0; i < labels.length; i++) {
var tmp = { data: [] };
tmp.label = labels[i];
tmp.borderColor = [tempbackgroundColor[i]];
tmp.backgroundColor = [tempbackgroundColor[i]];
tmp.borderWidth = 1;
tmp.data = [barData[i]];
dataSets.push(tmp);
}
if (data != '') {
$scope.trendChartLoading = '0';
}
showMBSLineChart(this.canvasId, labels, dataSets, "bar", this.area,true,false);
showMBSLineChart function
var showMBSLineChart = function (canvasId, labels, dataSets, chartType = 'line',xlabelstring="",ticksunitdisplay=true,labeldisplayx=false) {
var ctxL = document.getElementById(canvasId).getContext('2d');
var aspratio = 1;
var ticksdisplay = true;
var scalelabeldisplayx = false;
var scalestringx = xlabelstring;
if (chartType == 'line') {
aspratio = 1;
ticksdisplay = ticksunitdisplay;
scalelabeldisplayx = labeldisplayx;
} else if (chartType == 'bar') {
aspratio = 1;
ticksdisplay = ticksunitdisplay;
scalelabeldisplayx = labeldisplayx;
}
var myLineChart = new Chart(ctxL, {
type: chartType,
data: {
labels: labels,
datasets: dataSets
},
options: {
responsive: true,
legend: {
display: true,
labels: {
boxWidth: 8,
fontSize:10
}
},
aspectRatio: aspratio,
scales: {
xAxes: [{
ticks: {
display: ticksdisplay,
fontSize: 10
},
scaleLabel: {
display: scalelabeldisplayx,
labelString: scalestringx
},
}]
}
}
});
}
In time of calling the showMBSLinechart function just call with single array data.Like this
showMBSLineChart(this.canvasId, ["counts"], dataSets, "bar", this.area,false,true);
I want to do an horizontal bar with 2 yaxes, Where a bar can have a positive or negative value and positive side has a yaxis and the negative side has other yaxis like the image
This is my code JSFiddle.
I can't change the names of the second yaxes
I add arrays with the same values because i would want two yaxes, It is not necessary to use "chart.js" if you knows other library where i can it use, please tell me
var canvas = document.getElementById('myChart');
var extremo1=[-5, 3, 9, -11];
var extremo2=[-5, 3, 9, -11];
var data = {
labels: ["Visua_Verbal", "Secuencial_Global", "Sensitivo_Intuitivo", "Reflexivo_Activo"],
datasets: [
{
backgroundColor: 'rgba(63, 191, 191, 0.75)',
borderColor: 'rgba(63, 191, 191, 0.75)',
hoverBackgroundColor: 'rgba(191, 63, 63, 1)',
hoverBorderColor: 'rgba(191, 63, 63, 1)',
data: extremo1
},
{
backgroundColor: 'rgba(63, 191, 191, 0.75)',
borderColor: 'rgba(63, 191, 191, 0.75)',
hoverBackgroundColor: 'rgba(191, 63, 63, 1)',
hoverBorderColor: 'rgba(191, 63, 63, 1)',
data: extremo1
}
]
};
var option = {
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
display: true,
ticks: {
maxTicksLimit: 12
}
}],
yAxes: [{
position: "left",
display: true,
ticks: {
callback:(label,index,labels)=>{
label = label.match(/_(\w*)/)[1];
return label;
}}
},
{
position: "right",
display: true,
ticks: {
callback:(label,index,labels)=>{
return label ;
}
}
}]
},
legend: {
display: false
}
};
var myLineChart = new Chart(canvas,{
type: 'horizontalBar',
data:data,
options:option
});
In the snippet below I've set the options labels, type, offset on the y-axes to achieve the result you want. I've also removed unnecessary properties.
var canvas = document.getElementById('myChart');
var extremo = [-5, 3, 9, -11];
var data = {
datasets: [{
backgroundColor: 'rgba(63, 191, 191, 0.75)',
borderColor: 'rgba(63, 191, 191, 0.75)',
hoverBackgroundColor: 'rgba(191, 63, 63, 1)',
hoverBorderColor: 'rgba(191, 63, 63, 1)',
data: extremo
}]
};
var option = {
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
ticks: {
maxTicksLimit: 12
}
}],
yAxes: [{
labels: ['Verbal', 'Global', 'Reflexivo', 'Sensitivo']
},
{
position: 'right',
labels: ['Visual', 'Secuencial', 'Activo', 'Intuitivo'],
gridLines: {
display: false
},
type: 'category',
offset: true
}
]
},
legend: {
display: false
}
};
var myLineChart = new Chart(canvas, {
type: 'horizontalBar',
data: data,
options: option
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart">