Show text whitin the bar - jQuery plot Vertically stacked bar chart [duplicate] - javascript

This question already exists:
Stacked Bar Flot Chart - labels inside each series of Stacked Bar [duplicate]
Closed 8 years ago.
I would like to show labels on each series of the stacked bar.Any idea please. I have been looking with no luck.
For example if you have blue series text will be blue on the series of the stacked bar and so on.
It should be something like that as you can see in the image :
Here is my code:-
<div id="placeholder" style="width:600px;height:300px;"></div>
var data = [
{label: 'foo', color:'red', data: [[1,300], [2,300], [3,300], [4,300], [5,300]]},
{label: 'bar', color:'blue', data: [[1,800], [2,600], [3,400], [4,200], [5,0]]},
{label: 'baz', color:'yellow', data: [[1,100], [2,200], [3,300], [4,400], [5,500]]},
];
$.plot($("#placeholder"), data, {
series: {
stack: 1,
bars: {
show: true,
lineWidth: 1,
barWidth: 0.8,
order: 1,
fill: true,
label: {
show: true,
radius:0.7,
formatter: function(label, series) {
var result =[ <?php echo $red; ?> ,<?php echo $blue; ?> ,<?php
echo $yellow; ?>
];
if ( label == "red")
{
return '<div style="font-size:13px; text-align:center; left:-340px; top:-338px;
position:absolute; color:white;">'+label+'<br/>'+(result[0])+'</div>';
}
else if (label == "blue")
{
return '<div style="font-size:13px; text-align:center; left:-343px; top:-228px;
position:absolute; color:white;">'+label+'<br/>'+(result[1])+'</div>';
}
else if (label == "yellow")
{
return '<div style="font-size:13px; text-align:center; left:-325px; top:-220px;
position:absolute; color:white;">'+label+'<br/>'+(result[2])+'</div>';
}
},
background: {
opacity: 0.8,
}
}
},
yaxis : {
min : 0,
tickLength: 0
} ,
xaxis: {
tickLength: 0,
axisLabel: "Date",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Arial',
axisLabelPadding: 3,
color: "#838383",
timeformat: "%b/%y"
}
}
});

You should be able to use the valuelabels plugin to get this to work.
Reference: https://github.com/winne27/flot-valuelabels/wiki
Download: https://github.com/winne27/flot-valuelabels/blob/master/jquery.flot.valuelabels.js
Basic example: http://jsfiddle.net/WetNoodles/6b8n4nhe/1/
With the plugin, you can specify these options on each data series:
valueLabels: {
show: true,
valign: 'middle'
}

Related

Chart JS : Display the percentage of labels without getContext('2d')

I'm using the library chartJs to display the data that i get from my MySQL database.
In the fucntion below, AddValuesToNavigatorChart takes the browsers data and the percentage data and displays them on the pie chart.
What i need to know, is how to add '%' in my labels ?
I found few answer with getContent('2d').. using the old way, but it's not working.
This is the function :
function AddValuesToNavigatorChart(browsers, percentage) {
checkNavigatorChart()
const data = {
labels: browsers,
datasets: [{
data: percentage,
backgroundColor: [
'rgb(192,192,192)',
'rgb(255,0,0)',
'rgb(0,0,0)',
'rgb(105,105,105)'
],
hoverOffset: 4
}]
};
const config = {
tooltips: {
enabled: false
},
type: 'pie',
data: data,
plugins: [ChartDataLabels],
options: {
showTooltips: false,
plugins: {
datalabels: {
color: 'rgb(255,255,255)',
borderWidth: '2',
align: 'top'
},
legend: {
position: 'bottom',
align: 'center',
labels: {
boxWidth: 12,
padding: 15,
usePointStyle: true,
pointStyle: 'circle'
}
},
title: {
text: 'Navigator Chart',
display: true,
color: 'rgb(0,0,0)',
position: 'top'
}
}
}
};
const NavigatorChart = new Chart(
document.getElementById('NavigatorChart'),
config
);
}
Please provide the version of chartjs that you are using.
Did you mean you want to show the % in the label of the tooltip?
For version v3.8.0, here is a working code I have just made, Link
As in option, you can edit the label of tooltip as you want:
options: {
plugins: {
tooltip: {
callbacks: {
label: (tooltipItem) => {
//tooltipItem is for the slice of the pie you are hovering now
return ' ' + tooltipItem.parsed + '%';
},
}
}
}
}

Chart.js - change which data the legend uses for the coloured box

I have a bar chart that always shows 4 bars. The bars are coloured dynamically. It looks like the coloured box takes its colour from the first data. I would like to use the colour from the 4th (last) data value. Maybe the options:plugins:legend:label:sort function helps but I don't understand what it does.
options
const options = {
scales: {
x: {
grid: {
display: false,
color: 'rgba(0,0,0)'
}
},
y: {
display: false,
min: 0,
max: 4
},
},
plugins: {
legend: {
position: 'bottom'
}
}
}
So I don't know if I can change the data that the box color comes from, or if there is a config option somewhere where I can change it manually.
You can use the generateLabels function as described here.
Please take a look at below runnable sample code and see how it works.
new Chart('myChart', {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'My Dataset',
data: [300, 50, 100],
backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
}]
},
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color
}];
}
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" height="180"></canvas>
Following up with #uminder's answer, if you want to keep the hide/show chart and the line-through style after clicking on the legend, you can add the following line:
options: {
responsive: false,
plugins: {
legend: {
labels: {
generateLabels: chart => {
let ds = chart.data.datasets[0];
let color = ds.backgroundColor[ds.backgroundColor.length - 1];
return [{
datasetIndex: 0,
text: ds.label,
fillStyle: color,
strokeStyle: color,
+ hidden: !chart.isDatasetVisible(0)
}];
}
}
}
}
}

Bar chart legend adjustments - Chart JS

I'm new in Chart JS and I have a bar chart with the legend displayed bellow the chart:
var data = {
labels: [],
datasets: [{
label: 'Disk C',
backgroundColor: "#000080",
data: [80]
}, {
label: 'Disk D',
backgroundColor: "#d3d3d3",
data: [90]
},
{
label: 'Memory',
backgroundColor: "#add8e6",
data: [45]
}]
};
var ctx = document.getElementById("mybarChart");
ctx.height = 300;
var mybarChart = new Chart(ctx, {
type: 'bar',
responsive: true,
data: data,
options: {
legend: {
display: true,
position: 'bottom'
},
scales: {
yAxes: [{
display: false,
ticks: {
beginAtZero: true
},
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
xAxes: [{
display: false,
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
barPercentage: 0.5,
categoryPercentage: 0.5
}]
}
}
});
But the legend should be something like :
It is possible to make the colors rectangles much more smaller and the values to be displayed one below another because in my example the labels are displayed in a single row?
Unfortunately, there is no way to customize the default legend in the manner that you are wanting. Fortunately, however, chart.js thought of this and provided a mechanism for you to generate and style your own legend outside of the canvas object (using regular html/css).
You can use the legendCallback options property to define a method that generates your legend html and then call the chart .generateLegend() prototype method to place into your page. Here is what I mean.
HTML for my page.
<div style="width:25%;">
<canvas id="mybarChart"></canvas>
<div id="legend"></div>
</div>
Then I define how the legend will look in the 'legendCallback' option property.
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><div class="legendValue"><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"> </span>');
if (chart.data.datasets[i].label) {
text.push('<span class="label">' + chart.data.datasets[i].label + '</span>');
}
text.push('</div></li><div class="clear"></div>');
}
text.push('</ul>');
return text.join('');
}
Finally, I add the legend html to my page.
$('#legend').prepend(mybarChart.generateLegend());
As always, here is a codepen example showing a working solution. You can change your legend look and feel simply by changing the html that is generated by the callback and using css.

Update legend colors in ExtJS 6 chart

I have a bar chart with a legend in ExtJS 6.0.2.
I need to update the colors of the bars and of the legend when the user does an action (clicking on a pie slice in my case).
Updating the color of the bars works as intended, but the legend doesn't. Here is an example of what I do right now :
chart.getLegendStore().data.items.forEach(function(x){
x.data.mark = 'rgb(255,255,255)';
});
The colors are correctly set, but they only update when I click on the legend item. I guess it's because ExtJS has no way to know that the underlying store has been modified. I tried going up the callstack with the debugger but I didn't find anything useful.
Is there a better way to do what I want, or/and how to make the legend update instanly ?
EDIT: If it helps, here is how I update the bars :
serie.setConfig("colors", newColors);
EDIT2 : And here is the full chart code :
Ext.define('QuoteBarChart', {
extend: 'Ext.chart.CartesianChart',
alias: 'widget.quotebarchart',
xtype: 'quotebarchart',
requires: [
'Ext.chart.axis.Category',
'Ext.chart.axis.Numeric',
'Ext.chart.series.Bar',
'Ext.chart.series.Line',
'Ext.chart.theme.Muted',
'Ext.chart.interactions.ItemHighlight'
],
flex: 2,
height: 600,
theme: 'Muted',
itemId: 'chartId',
store: {
type: 'quote'
},
insetPadding: {
top: 40,
bottom: 40,
left: 20,
right: 40
},
axes: [{
type: 'numeric',
position: 'left',
fields: ['won', 'lost', 'open'],
minimum: 0,
grid: true,
titleMargin: 20,
title: 'Offres'
}, {
type: 'category',
position: 'bottom',
label: {
rotate: {
degrees: 45
}
},
fields: ['month']
}
],
series: [{
type: 'bar',
axis: 'left',
xField: 'month',
itemId: 'barId',
yField: ['open','lost','won'],
title: ['Ouvertes', 'Perdues','Gagnées'],
stacked: true,
fullStack: true,
colors: [
'rgb(64, 145, 186)', 'rgb(151, 65, 68)','rgb(140, 166, 64)'
],
highlight: {
strokeStyle: 'red',
fillStyle: 'black'
},
tooltip: {
trackMouse: true,
scope: this,
renderer: function (toolTip, storeItem, item) {
var name = "";
switch(item.field) {
case 'won': name = "Gagnées"; break;
case 'lost': name = "Perdues"; break;
case 'open': name = "Ouvertes"; break;
}
toolTip.setHtml("");
}
}
}],
legend: {
docked: 'bottom',
listeners: {
itemclick: 'onLegendItemClick',
itemmouseenter: 'onLegendItemHover'
}
}
)};
Ok, instead of modify colors of the series and colors of the legend, you can modify all of them in the same time doing this
chart.setColors(['red','blue','green']);
chart.redraw();
So you need to set colors on chart and not on series, and modify the array on button click.

Dojo Chart issues in naming label of X-axis name

I am new to dojo chart. I am trying to create a stacked column chart using dojo . I am trying to show bar chart with line chart using dojo chart.Chart is appear. But here is my problem is how can i write my x-axis label name which comes from my database.I want to naming each bar's name on X-axis. My actual values comes from database. I searches from all stack overflow suggestion,dojo guides and from others but i could not found any proper solution.So i request to you please help me where my code is wrong.So here i can rectify me for futures.
Here is my code index.php
<?php
include "connection.php";
$array = array();
$array1 = array();
$array2 =array();
$query1 = "SELECT name,rate1,rate2 FROM TEST";
$result = mysql_query($query1) or die ('Could not find Projects');
while ($rows = mysql_fetch_array($result)){
$array1[]=$rows['name'];
$array1[]=$rows['rate1'];
$array2[]=$rows['rate2'];
}
print_r($array1);
print_r (json_encode($array1,JSON_NUMERIC_CHECK));
print_r (json_encode($array2,JSON_NUMERIC_CHECK));
<html><head>
<link rel="stylesheet" href="dijit/themes/tundra/tundra.css">
<script>dojoConfig = {parseOnLoad: true}</script>
<script src='dojo/dojo.js'></script>
<script type="text/javascript">
require(["dojox/charting/Chart",
//"dojox/charting/plot2d/Lines",
"dojox/charting/axis2d/Default",
"dojox/charting/plot2d/StackedColumns",
"dojox/charting/action2d/Tooltip",
"dojo/ready",
"dojox/charting/widget/SelectableLegend"],
function(Chart, Default, StackedColumns, Tooltip, ready, SelectableLegend) {
ready(function() {
var chart1 = new Chart("chart1");
chart1.addPlot("stackedColumnsPlot", {
type: StackedColumns,
lines: true,
areas: true,
markers: true,
tension: "S"
});
chart1.addPlot("linesPlot", {
type: Lines,
markers: true,
stroke: {
width: 2
},
tension: 2
});
chart1.addAxis("x");
chart1.addAxis("y", {
vertical: true
});
chart1.addSeries("Series 1", <?php echo json_encode($array1,JSON_NUMERIC_CHECK); ?>
, {
plot: "stackedColumnsPlot",
stroke: {
color: "blue"
},
fill: "lightblue"
});
chart1.addSeries("Series 2", <?php echo json_encode($array2,JSON_NUMERIC_CHECK); ?>, {
plot: "stackedColumnsPlot",
stroke: {
color: "green"
},
fill: "lightgreen"
});
new Tooltip(chart1, "stackedColumnsPlot", {
text: function(chartItem) {
console.debug(chartItem);
return "Value: " + chartItem.run.data[chartItem.index] + "; Stacked Value: " + chartItem.y;
}
});
chart1.render();
new SelectableLegend({
chart: chart1,
horizontal: false
}, "chart1SelectableLegend");
});
});
</script>
This is my code what i am writing for stacked column chart.So suggest me how can i write label name of x-axis in my chart which comes from my database.
Add a label to the x axis:
Here are a few examples:
Use title property for one label for the entire axis.
chart.addAxis("x", {
min: 0, max: 100,
fontColor: "blue",
vertical: true,
fixLower: "major", fixUpper: "major",
title: "X axis title",
titleFont: "bold bold bold 12pt Arial,sans-serif",
titleOrientation: "axis"
});
For labels on each tick mark on the x axis:
var xAxisLabels = [{text: "Today",value: 1},{text: "-1",value: 2},{text: "-2",value: 3},{text: "-3",value: 4},{text: "-4",value: 5},{text: "-5",value: 6},{text: "-6",value: 7},{text: "WK-1",value: 8},{text: "WK-2",value: 9},{text: "WK-3",value: 10},{text: "WK-4",value: 11}];
chart.addAxis("x", {
labels: xAxisLabels,
fontColor: "blue",
majorTicks:true,
majorTickStep:1,
minorTicks:false,
max: 11
});
Not sure about the database part

Categories

Resources