Apex Chart Customer tool tip doesn't work - apexcharts

I am trying to use the custom tooltip from Apex Charts, have tried multiple examples online but they dont seem to work.. I am getting a tool tip but it seems like its the standard tooltip.
const { _getSum } = require("../helper/dynamicFormat");
const express = require("express");
const router = express.Router();
const { Validator } = require("../middlewares");
const resolvers = require("../resolvers");
const db = require("../models");
const moment = require("moment");
const _ = require("lodash");
const { getRandomColors } = require("../helper/colors");
router.get(
"/",
[Validator.check("query").not().isEmpty()],
Validator,
async (req, res, next) => {
try {
const { query } = req.query;
const options = JSON.parse(query);
let idleData=[
{
x: '3R4785',
y: [
new Date(1789, 3, 1,18,30).getTime(),
new Date(1789, 3, 1,19,30).getTime(),
]},{
x: '3R4785',
y: [
new Date(1789, 3, 1,21).getTime(),
new Date(1789, 3, 1,22).getTime(),
]
}
]
let drivingData= [
{
x: '3R4785',
y: [
new Date(1789, 3, 1,22).getTime(),
new Date(1789, 3, 1,23).getTime()
]
},
]
let parkingData=[
{
x: '3R4785',
y: [
new Date(1789, 3, 1, 23).getTime(),
new Date(1789, 3, 1,24).getTime(),
]
},
]
res.render("millage", {
options: JSON.stringify({
series: [
{
name: 'Idle',
data:idleData
},
{
name: 'Driving',
data:drivingData
},
{
name: 'Parking',
data: parkingData
},
],
chart: {
height: 350,
type: 'rangeBar'
},
plotOptions: {
bar: {
horizontal: true,
barHeight: '50%',
rangeBarGroupRows: true
}
},
colors: [
"#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0",
"#3F51B5", "#546E7A", "#D4526E", "#8D5B4C", "#F86624",
"#D7263D", "#1B998B", "#2E294E", "#F46036", "#E2C044"
],
fill: {
type: 'solid'
},
xaxis: {
type: 'datetime',
format: 'hh mm'
},
tooltip: {
custom: function({series, seriesIndex, dataPointIndex, w}) {
var data = w.globals.initialSeries[seriesIndex].data[dataPointIndex];
console.log("tooltip",series,seriesIndex,dataPointIndex,w)
return '<ul>' +
'<li><b>Price</b>: ' + data.x + '</li>' +
'<li><b>Number</b>: ' + data.y + '</li>' +
'</ul>';
}
},
legend: {
position: 'right'
},
}),
});
} catch (error) {
console.log("🚀 ~ file: millage.js ~ line 13 ~ error", error);
}
}
);
module.exports = router;
I have tried multiple examples online, but nothing changes the standard tooltip.. I get a tooltip but it's not the one I want. Also when I try to console out the tooltip function, nothing comes..
I tried also made sure to use the latest apext charts
this is how I render the component:-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/apexcharts#latest"></script>
</head>
<body>
{{{body}}}
</body>
</html>
<div id="chart"></div>
<script>
const defaultOptions = {
}
const options = JSON.parse(`{{options}}`.replace(/"/g, '"'));
var chart = new ApexCharts(document.getElementById("chart"), { ...defaultOptions, ...options });
chart.render();
</script>

Related

How to add a custom plugin to chart.js

I'm having a hard time creating my first plugin for chart.js
After watching a few tutorials, I made the code below expecting to get "chart" in the console but nothing happens.
What am I missing here?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js#4.1.1/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation#2.1.1/dist/chartjs-plugin-annotation.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script>
const ctx = document.getElementById('myChart');
const tooltipNote = {
id: 'tooltipNote',
beforeDraw: chart => {
console.log('chart');
}
}
new Chart(ctx, {
type: 'line',
responsive: true,
data: {
labels: ['', '', '', '', '', ''],
datasets: [{
data: [42, 119, 53, 55, 62, 53],
}]
},
options: {
scales: {
y: {
suggestedMin: 0,
offset: true
},
},
plugins: {
legend: {
display: false
},
tooltipNote: {
},
},
},
});
</script>
</body>
</html>
You never register your plugin as documented here: https://www.chartjs.org/docs/latest/developers/plugins.html
You can either only register it specific chart instances like so:
const tooltipNote = {
id: 'tooltipNote',
beforeDraw: chart => {
console.log('chart');
}
};
new Chart(ctx, {
data: data,
options: options,
plugins: [tooltip note]
});
Or you can register it globally so it is available to all your instances:
const tooltipNote = {
id: 'tooltipNote',
beforeDraw: chart => {
console.log('chart');
}
}
Chart.register(tooltipNote);
What you did was only define the options as an empty object for your plugin.

Class does not have id chartjs

I need a help!
const annotationLinePlugin = {
renderAnnotationLine: function(chartInstance, line) {
let datasetMeta = chartInstance.getDatasetMeta(line.datasetIndex);
let context = chartInstance.chart.ctx;
let datasetModel = datasetMeta.data[line.dataIndex]._model;
const xBarCenter = datasetModel.x
const barWidth = datasetModel.width;
const xStart = xBarCenter - (barWidth / 2) - 4;
const xEnd = xBarCenter + (barWidth / 2) + 4;
const yAxisID = datasetMeta.yAxisID;
const yCoordinate = chartInstance.scales[yAxisID].getPixelForValue(line.yCoordinate);
context.beginPath();
context.strokeStyle = line.color;
context.lineWidth = line.width;
context.moveTo(xStart, yCoordinate);
context.lineTo(xEnd, yCoordinate);
context.stroke();
if (typeof line.label !== typeof undefined) {
context.textAlign = 'center';
context.fillStyle = line.color;
context.fillText(line.label, yCoordinate, xEnd + 7);
}
},
afterDatasetsDraw: function(chart, easing) {
if (chart.data.datasets.length < 1) {
return;
}
if (chart.config.lines) {
chart.config.lines.map(line => {
this.renderAnnotationLine(chart, line);
});
}
}
};
Chart.register(annotationLinePlugin);
I get a error in browser : Uncaught Error : class does not have id
picture with errors
I had chartjs2, i had to migrate to chartjs3.In chartjs2, there were red lines on every chart object, after switching to chaartjs3, these lines were gone, in the record of cases that Chart.plugins.register was replaced by chart.register, I replaced it, but still nothing worked.
There were the lines :
lines
index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chart.js 2 to 3</title>
</head>
<body>
<div>
<canvas id="сhart"></canvas>
</div>
</body>
<script src="./chartjs3/chart.js"></script>
<script src="./chartjs3/chart.min.js"></script>
<script src="./chartjs3/chartjs-plugin-annotation.js"></script>
<script src="./chartjs3/chartjs-plugin-annotation.min.js"></script>
<script src="./chartjs3/chartjs-plugin-annotationLine.js"></script>
<script src="./chartjs3/chartjs-plugin-datalabels.js"></script>
<script src="./chartjs3/chartjs-plugin-datalabels.min.js"></script>
<script src="./chartjs3/hammer.min.js"></script>
<script>
const ctx = document.getElementById("сhart").getContext("2d");
const options = {
type: "bar",
responsive: true,
maintainAspectRatio: false,
title: { display: false },
tooltips: {
mode: "index",
intersect: true,
filter: (tooltipItem, chartData) => {
return (
!chartData.datasets[tooltipItem.datasetIndex].hideFromTooltip &&
(chartData.datasets[tooltipItem.datasetIndex].yAxisID == "R" ||
tooltipItem.yLabel > 0)
);
},
callbacks: {
label: function (tooltipItem, chartData) {
return (
chartData.datasets[tooltipItem.datasetIndex].label +
": " +
tooltipItem.yLabel.round(0)
);
},
},
},
animation: {
duration: 500,
easing: "linear",
},
plugins: {
datalabels: {
display: function (context) {
const axisMax = context.chart.scales["L"]
? context.chart.scales["L"].max
: 0;
const datasetLabelsSettings =
context.chart.data.datasets[context.datasetIndex].datalabels;
const isLabelOutside =
datasetLabelsSettings &&
datasetLabelsSettings.anchor === "end" &&
datasetLabelsSettings.align === "end";
return (
context.chart.isDatasetVisible(context.datasetIndex) &&
report.chartSettings.showDataLabels &&
((isLabelOutside &&
context.dataset.data[context.dataIndex] > 0) ||
context.dataset.data[context.dataIndex] >
axisMax * HIDE_DATALABELS_Y_LEVEL) &&
context.dataset.type !== "line"
);
},
formatter: (x) => {
return (x || 0).round(0);
},
},
},
legend: {
display: true,
onClick: function (event, legendItem) {
var index = legendItem.datasetIndex,
meta = null;
var tag = chart.data.datasets[index].tag;
var meta = chart.getDatasetMeta(index);
if (tag || isNumeric(tag)) {
chart.data.datasets
.filter((x) => x.tag == tag)
.forEach((item) => {
item.hidden = item.forcedHidden || !item.hidden;
});
} else {
meta.hidden = meta.hidden === null ? !meta.hidden : null;
}
chart.update();
},
position: "top",
labels: {
usePointStyle: true,
filter: function (legendItem, chartData) {
return (
chartData.datasets[legendItem.datasetIndex].displayInLegend ||
chartData.datasets[legendItem.datasetIndex].displayInLegend ==
undefined
);
return false;
},
},
},
cales: {
xAxes: [
{
stacked: true,
scaleLabel: {
display: true,
labelString: "Период",
},
},
],
yAxes: [
{
id: "L",
type: "linear",
position: "left",
stacked: true,
scaleLabel: {
display: true,
labelString: "Трудозатраты, чел-мес",
},
},
],
},
lines: [
5553, 5454, 5399, 5290, 5260, 4927, 4565, 4649, 5324, 5624, 5710, 5766,
5827, 5829, 5831, 5832, 5833, 5835, 5835, 5836, 5836, 5836, 5837, 583,
].map((x, i) => {
return {
datasetIndex: 0,
dataIndex: i,
yCoordinate: x,
color: "salmon",
width: 3,
};
}),
data: {
labels: [
"2022-01",
"2022-02",
"2022-03",
"2022-04",
"2022-05",
"2022-06",
"2022-07",
"2022-08",
"2022-09",
"2022-10",
"2022-11",
"2022-12",
"2023-01",
"2023-02",
"2023-03",
"2023-04",
"2024-05",
"2023-06",
"2023-07",
"2023-08",
"2023-09",
"2023-10",
"2023-11",
"2023-12",
],
datasets: [
{
label: "ОПИ (ресурсный профиль)",
findId: "ОПИ",
tag: "ОПИ",
type: "bar",
borderWidth: 1,
stack: "cnt",
groupType: "cnt",
backgroundColor: "#2196f3",
fill: false,
pointStyle: "rect",
detailMode: "point",
data: [
5356, 5802, 6105, 6258, 6524, 6690, 6697, 7348, 6578, 5742, 4626,
3678, 4809, 6038, 5891, 4526, 3637, 3601, 3471, 3618, 3548, 3428,
3330, 3448, 5031,
],
displayInLegend: false,
datalabels: {
anchor: "end",
align: "end",
offset: 0,
color: function (context) {
return "#2196f3";
},
},
},
],
},
};
const сhart = new Chart(ctx, options);
</script>
</html>
The plugin needs to have an unique id.
You could add an id (see following example):
const annotationLinePlugin = {
id: 'annotationLine',
....
}
Be also aware the afterDatasetsDraw hook has got a different signature (arguments).
https://www.chartjs.org/docs/latest/api/interfaces/Plugin.html#afterdatasetsdraw

Vue 3 & Chart JS not updating labels

I'm trying to make a simple Vue3 app which show graphs using Chart.js
For this I'm trying to replicate the code shown in the vue-chart-3 plugin doc, which shows an example using a Doughnut chart
My objective is to show a Line graph with a horizontal time axis
The code is a simple App.vue which template is
<template>
<LineChart v-bind="lineChartProps" />
</template>
And the script part:
<script lang="ts">
import { computed, defineComponent, ref } from "vue";
import { LineChart, useLineChart } from "vue-chart-3";
import { Chart, ChartData, ChartOptions, registerables } from "chart.js";
Chart.register(...registerables);
export default defineComponent({
name: "App",
components: { LineChart },
setup() {
const dataValues = ref([30, 40, 60, 70, 5]);
const dataLabels = ref(["Paris", "Nîmes", "Toulon", "Perpignan", "Autre"]);
const toggleLegend = ref(true);
const testData = computed<ChartData<"doughnut">>(() => ({
labels: dataLabels.value,
datasets: [
{
data: dataValues.value,
backgroundColor: [
"#77CEFF",
"#0079AF",
"#123E6B",
"#97B0C4",
"#A5C8ED",
],
},
],
}));
const options = computed<ChartOptions<"doughnut">>(() => ({
scales: {
myScale: {
type: "logarithmic",
position: toggleLegend.value ? "left" : "right",
},
},
plugins: {
legend: {
position: toggleLegend.value ? "top" : "bottom",
},
title: {
display: true,
text: "Chart.js Doughnut Chart",
},
},
}));
const { lineChartProps, lineChartRef } = useLineChart({
chartData: testData,
options,
});
function switchLegend() {
toggleLegend.value = !toggleLegend.value;
}
return {
switchLegend,
testData,
options,
lineChartRef,
lineChartProps,
};
},
mounted() {
if (localStorage.data == undefined) {
localStorage.data = JSON.stringify(this.data);
} else {
this.data = localStorage.data;
}
let dataProcessed = JSON.parse(this.data);
// console.log(JSON.parse(this.data));
console.log(dataProcessed.data);
var dates = [];
// Obtain dates from dataProcessed Array
for (var i = 0; i < dataProcessed.data.length; i++) {
dates.push(dataProcessed.data[i].date);
}
this.testData.labes = dates;
console.log(dates);
},
});
</script>
The objective is that the mounted hook gets certain parameters of the LocalStorage and put them in the "labels" array of the "testData" variable, which is the one which aparently stores the X axis data of the chart.
In the VUE developer tool, it can be seen how this assignation process is done correctly, but in the chart of the left side, the data have not been updated.
Thank you for your help :D

Chartjs v. 3.7.1 Zoom out not working after zooming in too much

I am realtively new in front end and Chartjs. My problem is when I zoom in more than a certain point I can not zoom out back. I tried mouse wheel option and added a "zoom out" button but both not working. When I zoom in just a little I dont face the same problem. I tried on Chrome and Edge browsers, both has the same behavior.
CahartJs version: 3.7.1
chartjs-plugin-zoom version: 1.2.0
Note: Second graph is for data decimation which is irrelevant with current problem.
script.js and index.html:
//data creation
let labels2 = [];
let data2 = []
i = 0
k = 0
while (k < 250) {
if (i < 10) {
let last_hall = 600
data2.push(last_hall)
labels2.push(k);
i++
}
if (i >= 10) {
let last_hall = 500
data2.push(last_hall)
labels2.push(k);
i++
if (i == 20) {
for (let j = 0; j < 30; j++) {
let last_hall = getRandomInt(800, 1300)
data2.push(last_hall)
labels2.push(k);
k++
}
i = 0
}
}
k++
}
//data2 = data2.fill(0).map(() => Math.random());
// let labels2 = [];
// let i = 0;
// data2.forEach(element => {
// labels2.push(i);
// i++;
// });
let data3 = [];
data3 = data2;
let labels3 = [];
labels3 = labels2;
ColorArr = ["red", "blue", "red"]
let backgroundColorArr = [];
let backgroundColorArr2 = [];
var ctx = document.getElementById('myChart2').getContext('2d');
var ctx2 = document.getElementById('myChart3').getContext('2d');
const up = (ctx, value) => ctx.p0.parsed.y >= ctx.p1.parsed.y ? value : undefined;
const down = (ctx, value) => ctx.p0.parsed.y < ctx.p1.parsed.y ? value : undefined;
const up2 = (ctx2, value) => ctx2.p0.parsed.y >= ctx2.p1.parsed.y ? value : undefined;
const down2 = (ctx2, value) => ctx2.p0.parsed.y < ctx2.p1.parsed.y ? value : undefined;
data2.forEach(element => {
backgroundColorArr.push(ColorArr[i % 3]);
i++;
});
backgroundColorArr2 = backgroundColorArr;
//Decimation
// if (data3.length > 1000) {
// var datastep = Math.floor(data3.length / 1000) //always show 1000 values from all data
// console.log(datastep);
// for (i = 0; i < 1000; i++) {
// data3[i] = data3[i * datastep];
// backgroundColorArr2[i] = backgroundColorArr2[i * datastep];
// labels3[i] = labels3[i * datastep];
// }
// }
// console.log(labels3)
// data3 = data3.slice(0, 1000);
// labels3 = labels3.slice(0, 1000);
// backgroundColorArr2 = backgroundColorArr2.slice(0, 1000);
let chart3 = new Chart(ctx, {
type: 'line',
data: {
labels: labels2,
datasets: [{
data: data2,
fill: true,
//backgroundColor: backgroundColorArr[ctx.p0DataIndex],
segment: {
borderColor: ctx => up(ctx, 'rgba(75,192,192,1)') || down(ctx, "red"),
backgroundColor: ctx => up(ctx, 'rgba(75,192,192,1)') || down(ctx, "red"), //backgroundColorArr[ctx.p0DataIndex]
},
}]
},
options: {
//parsing: false,
scales: {
x: {
ticks: {
maxTicksLimit: 10,
autoSkip: true,
}
},
y: {
beginAtZero: true
}
},
datasets: {
parsing: false,
line: {
pointRadius: 0 // disable for all `'line'` datasets
}
},
plugins: {
// decimation: {
// algorithm: 'lttb',
// enabled: true,
// samples: 20
// },
zoom: {
pan: {
enabled: true,
mode: 'x',
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true
},
mode: 'x',
}
}
}
}
});
let chart2 = new Chart(ctx2, {
type: 'line',
data: {
labels: labels3,
datasets: [{
data: data3,
fill: true,
//backgroundColor: backgroundColorArr[ctx.p0DataIndex],
segment: {
borderColor: ctx2 => up2(ctx2, 'rgba(75,192,192,1)') || down(ctx2, "red"),
backgroundColor: ctx2 => up2(ctx2, 'rgba(75,192,192,1)') || down(ctx2, "red"), //backgroundColorArr[ctx.p0DataIndex],
},
}]
},
options: {
//parsing: false,
scales: {
x: {
ticks: {
maxTicksLimit: 10,
autoSkip: true,
}
},
y: {
beginAtZero: true
}
},
datasets: {
parsing: false,
line: {
pointRadius: 0 // disable for all `'line'` datasets
}
},
plugins: {
// decimation: {
// algorithm: 'lttb',
// enabled: true,
// samples: 20
// },
zoom: {
pan: {
enabled: true,
mode: 'x',
},
zoom: {
//enabled: true,
wheel: {
enabled: true,
},
pinch: {
enabled: true
},
mode: 'x',
}
}
}
}
});
function resetZoom() {
chart2.resetZoom();
}
function resetZoom2() {
chart3.resetZoom();
}
function zoomButton() {
chart2.zoom(1.1);
}
function zoomButton2() {
chart3.zoom(1.3);
}
function zoomOutButton() {
chart2.zoom(0.9);
}
function zoomOutButton2() {
chart3.zoom(0.7);
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Charts, Charts, Charts</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.1"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"
integrity="sha512-UXumZrZNiOwnTcZSHLOfcTs0aos2MzBWHXOHOuB0J/R44QB0dwY5JgfbvljXcklVf65Gc4El6RjZ+lnwd2az2g=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/1.2.0/chartjs-plugin-zoom.min.js"
integrity="sha512-TT0wAMqqtjXVzpc48sI0G84rBP+oTkBZPgeRYIOVRGUdwJsyS3WPipsNh///ay2LJ+onCM23tipnz6EvEy2/UA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<button onclick="download_csv_file()"> Download CSV </button>
<h1>Charts, Charts, Charts</h1>
<div class="container">
<div class="row">
<div class="col-6 chart">
<canvas id="myChart2" width="1000" height="800"></canvas>
<button onclick="resetZoom2()"> Reset </button>
<button onclick="zoomOutButton2()"> Zoom Out </button>
<button onclick="zoomButton2()"> Zoom In</button>
</div>
</div>
<div class="row">
<div class="col-6 chart">
<canvas id="myChart3" width="1000" height="800"></canvas>
<button onclick="resetZoom()"> Reset </button>
<button onclick="zoomButton()"> Zoom In</button>
<button onclick="zoomOutButton()"> Zoom Out</button>
</div>
<div class="col-6 chart">
<canvas id="myChart4" width="500" height="400"></canvas>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Just had the same problem.
https://github.com/chartjs/chartjs-plugin-zoom/issues/696
Possible solution:
Don't use numbers as labels, use String versions of them
by using .toString() on items of the array.
[1, 2, 3] -> ["1", "2", "3"]

Power bi api - Label width needs adjustment

My vertical labels in the graph are getting cut off.
Is there a way to set/increase the label width?
Please see the image below.
The left hand labels need more width. (Y axis labels)
Power BI Column Graph Using API
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link href="https://raw.githubusercontent.com/Microsoft/PowerBI-visuals/master/lib/visuals.css" rel="stylesheet">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/externals.min.js"> </script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/powerbi-visuals.js" ></script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/PowerBIVisualsPlayground.js"></script>
<style>
.visual {
'background-color' : 'white',
'padding' : '10px',
'margin' : '5px'
}
</style>
</head>
<body>
<h1> hello </h1>
<div class="visual"></div>
<script type="text/javascript">
var createDataView = function () {
var DataViewTransform = powerbi.data.DataViewTransform;
var fieldExpr = powerbi.data.SQExprBuilder.fieldExpr({ column: { entity: "table1", name: "country" } });
var categoryValues = ["Australia", "Canada", "France", "Germany", "United Kingdom", "United States"];
var categoryIdentities = categoryValues.map(function (value) {
var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value));
return powerbi.data.createDataViewScopeIdentity(expr);
});
// Metadata, describes the data columns, and provides the visual with hints
// so it can decide how to best represent the data
var dataViewMetadata = {
columns: [
{
displayName: 'Country',
queryName: 'Country',
type: powerbi.ValueType.fromDescriptor({ text: true })
},
{
displayName: 'Sales Amount (2014)',
isMeasure: true,
format: "$0",
queryName:'sales1',
type: powerbi.ValueType.fromDescriptor({ numeric: true }),
}
,
{
displayName: 'Sales Amount (2013)',
isMeasure: true,
format: "$0",
queryName:'sales2',
type: powerbi.ValueType.fromDescriptor({ numeric: true })
}
],
};
var columns = [
{
source: dataViewMetadata.columns[1],
// Sales Amount for 2014
values: [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34],
},
{
source: dataViewMetadata.columns[2],
// Sales Amount for 2013
values: [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34].reverse()
}
];
var dataValues = DataViewTransform.createValueColumns(columns);
var dataView = {
metadata: dataViewMetadata,
categorical: {
categories: [{
source: dataViewMetadata.columns[0],
values: categoryValues,
identity: categoryIdentities,
}],
values: dataValues
}
};
return dataView;
};
function createDefaultStyles(){
var dataColors = new powerbi.visuals.DataColorPalette();
return {
titleText: {
color: { value: 'rgba(51,51,51,1)' }
},
subTitleText: {
color: { value: 'rgba(145,145,145,1)' }
},
colorPalette: {
dataColors: dataColors,
},
labelText: {
color: {
value: 'rgba(51,51,51,1)',
},
fontSize: '11px'
},
isHighContrast: false,
};
}
function createVisual() {
var pluginService = powerbi.visuals.visualPluginFactory.create();
var defaultVisualHostServices = powerbi.visuals.defaultVisualHostServices;
var width = 600;
var height = 400;
var element = $('.visual');
element.height(height).width(width);
// Get a plugin
var visual = pluginService.getPlugin('columnChart').create();
powerbi.visuals.DefaultVisualHostServices.initialize();
visual.init({
// empty DOM element the visual should attach to.
element: element,
// host services
host: defaultVisualHostServices,
style: createDefaultStyles(),
viewport: {
height:height,
width: width
},
settings: { slicingEnabled: true },
interactivity: { isInteractiveLegend: false, selection: false },
animation: { transitionImmediate: true }
});
// Call update to draw the visual with some data
visual.update({
dataViews: [createDataView()] ,
viewport: {
height: height,
width: width
},
duration: 0
});
}
createVisual();
</script>
</body>
</html>
To do it automatically, you'll need to measure the text and allocate sufficient room. You might try an approach similar to this. Alternately, you could add a property for label size in the formatting pane and let your users override the default.