How to remove the y axis ticks in flot - javascript

I am using flot to generate bar graphs.
Here is my code bar graph code
I need to make the y axis tick to disappear.
I need to put some label on the top of each bar
How to do it?

Okay, after a lot of mucking around with Flot and downloading the source, I finally figured out a good starting point for you.
The jsFiddle demo is here.
The guts of the code is using a hook for drawSeries which draws the label:
function drawSeriesHook(plot, canvascontext, series) {
var ctx = canvascontext,
plotOffset = plot.offset(),
labelText = 'TEST', // customise this text, maybe to series.label
points = series.datapoints.points,
ps = series.datapoints.pointsize,
xaxis = series.xaxis,
yaxis = series.yaxis,
textWidth, textHeight, textX, textY;
// only draw label for top yellow series
if (series.label === 'baz') {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineWidth = series.bars.lineWidth;
ctx.fillStyle = '#000'; // customise the colour here
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null) continue;
textWidth = ctx.measureText(labelText).width; // measure how wide the label will be
textHeight = parseInt(ctx.font); // extract the font size from the context.font string
textX = xaxis.p2c(points[i] + series.bars.barWidth / 2) - textWidth / 2;
textY = yaxis.p2c(points[i + 1]) - textHeight / 2;
ctx.fillText(labelText, textX, textY); // draw the label
}
ctx.restore();
}
}
See the comments for where you can customise the label.
To remove the y-axis ticks, that is just a simple option setting. In addition, you can work out the maximum y-value for each of the bar stacks and then add about 100 to that to set a maximum Y value that will allow for the space taken up by the labels. The code for all of that then becomes:
// determine the max y value from the given data and add a bit to allow for the text
var maxYValue = 0;
var sums = [];
$.each(data,function(i,e) {
$.each(this.data, function(i,e) {
if (!sums[i]) {
sums[i]=0;
}
sums[i] += this[1]; // y-value
});
});
$.each(sums, function() {
maxYValue = Math.max(maxYValue, this);
});
maxYValue += 100; // to allow for the text
var plot = $.plot($("#placeholder"), data, {
series: {
stack: 1,
bars: {
show: true,
barWidth: 0.6,
},
yaxis: {
min: 0,
tickLength: 0
}
},
yaxis: {
max: maxYValue, // set a manual maximum to allow for labels
ticks: 0 // this line removes the y ticks
},
hooks: {
drawSeries: [drawSeriesHook]
}
});
That should get you started. You can take it from here, I'm sure.

Related

How can I draw a line to the highest datapoint in chart js?

I've been consuming the Chart JS documentation but I think this is probably more computer science / math based of a question. I'm trying to draw a line that extends from the bottom of my chart to the top of the highest data point. Here's a link to a working code example: https://stackblitz.com/edit/react-pvzbwc
The idea is for the chart to look something like this where the point ends exactly at the top of the data: https://i.stack.imgur.com/L8d0H.jpg
Here's what I have so far for my after draw hook:
// draw a line when someone hovers over a data point
afterDatasetDraw: (chart) => {
// console.log(chart)
if (chart.tooltip._active && chart.tooltip._active.length) {
const activePoint = chart.tooltip._active[0];
console.log(activePoint.tooltipPosition())
const ctx = chart.ctx;
const y_axis = chart.scales['y-axis-0'];
const x = activePoint.tooltipPosition().x;
const yData = activePoint._chart.config.data.datasets[activePoint._datasetIndex].data[activePoint._index].y;
const topY = y_axis.top;
const bottomY = y_axis.bottom;
// draw line
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 2;
ctx.strokeStyle = '#000';
ctx.stroke();
ctx.restore();
}
}
It works pretty well when I need to draw a line straight up through the top, but not when I want just to see it at the top of the highest datapoint. What I've noticed is that topY is a static unchanging number. I'm wondering if there's a way I can calculated the top position based on the cartesian points of the chart?
Any insight is definitely appreciated.
After some struggle I've answered the question. It was a lot more simple than I made the problem out to be. It turns out I just needed to calculate the ratio between the datapoints and the graph in pixels, and then implement a line at that point.
I've put this into a plugin with the API:
/// default values
lineHeightAnnotation: {
// defaults to have line to the highest data point on every tick
always: true,
// optionally, only have line draw to the highest datapoint nearest the user's hover position
hover: false,
// colors of the line
color: '#000',
// name of yAxis
yAxis: 'y-axis-0',
// weight of the line
lineWeight: 1.5,
/// sets shadow for ALL lines on the canvas
shadow: {
// color of the shadow
color: 'rgba(0,0,0,0.35)',
// blur of the shadow
blur: 10,
/// shadow offset
offset: {
// x offset
x: 0,
// y offset
y: 3
}
},
// dash defaults at [10, 10]
noDash: true,
}
Logic:
/**
* Vars
* maxY - the tallest data point on the graph
* tickMax - the tallest tick on the y axis
* bottomY - the lowest point of the graph
* additionalOffsets = dataset.borderWidth * 2
*
* bottomY * maxY
* highestDataY = bottomY - ------------------- + additionOffsets
* tickMax
*/
Function:
afterDatasetDraw: (chart) => {
// draw a dashed line when someone hovers over a data point
if (chart.tooltip._active && chart.tooltip._active.length) {
const activePoint = chart.tooltip._active[0];
const ctx = chart.ctx;
const x = activePoint.tooltipPosition().x;
const yAxis = chart.scales['y-axis-0'];
const tickMax = yAxis.ticksAsNumbers[0] // first index is always the tallest
const tickLow = yAxis.ticksAsNumbers[yAxis.ticksAsNumbers.length - 1]
const topY = yAxis.top; // clientRect.top + chart.padding.y
const bottomY = yAxis.bottom; // clientRect.bottom
let maxY = 1;
let borderWidth = 0;
const datasets = chart.config.data.datasets
datasets.forEach((set, i) => {
// get maximum Y value
// get borderWidth of that dataset
let point = set.data[activePoint._index].y
if(point > maxY) {
maxY = parseInt(point, 10) - parseInt(set.borderWidth, 10)
borderWidth = parseInt(set.borderWidth, 10)
}
});
let yBRatio = bottomY * (maxY - tickLow)
let tMRatio = yBRatio / (tickMax - tickLow)
let highestDataY = bottomY - tMRatio + (borderWidth * 2)
// draw line
ctx.save();
ctx.beginPath();
ctx.setLineDash([10, 10]);
ctx.moveTo(x, highestDataY);
ctx.lineTo(x, bottomY);
ctx.lineWidth = 1.5;
ctx.strokeStyle = '#000';
ctx.stroke();
ctx.restore();
}

How can I evenly distribute ticks when using maxTicksLimit?

I made a line chart using Chart.js version 2.1.3.
var canvas = $('#gold_chart').get(0);
var ctx = canvas.getContext('2d');
var fillPatternGold = ctx.createLinearGradient(0, 0, 0, canvas.height);
fillPatternGold.addColorStop(0, '#fdca55');
fillPatternGold.addColorStop(1, '#ffffff');
var goldChart = new Chart(ctx, {
type: 'line',
animation: false,
data: {
labels: dates,
datasets: [{
label: '',
data: prices,
pointRadius: 0,
borderWidth: 1,
borderColor: '#a97f35',
backgroundColor: fillPatternGold
}]
},
title: {
position: 'bottom',
text: '\u7F8E\u5143 / \u76CE\u53F8'
},
options: {
legend: {
display: false
},
tooltips: {
callback: function(tooltipItem) {
return tooltipItem.yLabel;
}
},
scales: {
xAxes: [{
ticks: {
maxTicksLimit: 8
}
}]
}
}
});
The output is as follow:
As you can see, I limited the maximum count of ticks to 8 via maxTicksLimit. However, the distribution is not even. How can I make the ticks distribute evenly?
p.s. there are always 289 records in the dataset, and the data is recorded every 5 minutes. Sample values of prices variable are:
[
{"14:10", 1280.3},
{"14:15", 1280.25},
{"14:20", 1282.85}
]
I tried different values of maxTicksLimit, and the results are still not distributed evenly.
Chart.js uses an integral skipRatio (to figure out how many labels to skip). With Chart.js v2.1.x, you can write your own plugin to use a fractional skipRatio
Preview
Script
Chart.pluginService.register({
afterUpdate: function (chart) {
var xScale = chart.scales['x-axis-0'];
if (xScale.options.ticks.maxTicksLimit) {
// store the original maxTicksLimit
xScale.options.ticks._maxTicksLimit = xScale.options.ticks.maxTicksLimit;
// let chart.js draw the first and last label
xScale.options.ticks.maxTicksLimit = (xScale.ticks.length % xScale.options.ticks._maxTicksLimit === 0) ? 1 : 2;
var originalXScaleDraw = xScale.draw
xScale.draw = function () {
originalXScaleDraw.apply(this, arguments);
var xScale = chart.scales['x-axis-0'];
if (xScale.options.ticks.maxTicksLimit) {
var helpers = Chart.helpers;
var tickFontColor = helpers.getValueOrDefault(xScale.options.ticks.fontColor, Chart.defaults.global.defaultFontColor);
var tickFontSize = helpers.getValueOrDefault(xScale.options.ticks.fontSize, Chart.defaults.global.defaultFontSize);
var tickFontStyle = helpers.getValueOrDefault(xScale.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle);
var tickFontFamily = helpers.getValueOrDefault(xScale.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily);
var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily);
var tl = xScale.options.gridLines.tickMarkLength;
var isRotated = xScale.labelRotation !== 0;
var yTickStart = xScale.top;
var yTickEnd = xScale.top + tl;
var chartArea = chart.chartArea;
// use the saved ticks
var maxTicks = xScale.options.ticks._maxTicksLimit - 1;
var ticksPerVisibleTick = xScale.ticks.length / maxTicks;
// chart.js uses an integral skipRatio - this causes all the fractional ticks to be accounted for between the last 2 labels
// we use a fractional skipRatio
var ticksCovered = 0;
helpers.each(xScale.ticks, function (label, index) {
if (index < ticksCovered)
return;
ticksCovered += ticksPerVisibleTick;
// chart.js has already drawn these 2
if (index === 0 || index === (xScale.ticks.length - 1))
return;
// copy of chart.js code
var xLineValue = this.getPixelForTick(index);
var xLabelValue = this.getPixelForTick(index, this.options.gridLines.offsetGridLines);
if (this.options.gridLines.display) {
this.ctx.lineWidth = this.options.gridLines.lineWidth;
this.ctx.strokeStyle = this.options.gridLines.color;
xLineValue += helpers.aliasPixel(this.ctx.lineWidth);
// Draw the label area
this.ctx.beginPath();
if (this.options.gridLines.drawTicks) {
this.ctx.moveTo(xLineValue, yTickStart);
this.ctx.lineTo(xLineValue, yTickEnd);
}
// Draw the chart area
if (this.options.gridLines.drawOnChartArea) {
this.ctx.moveTo(xLineValue, chartArea.top);
this.ctx.lineTo(xLineValue, chartArea.bottom);
}
// Need to stroke in the loop because we are potentially changing line widths & colours
this.ctx.stroke();
}
if (this.options.ticks.display) {
this.ctx.save();
this.ctx.translate(xLabelValue + this.options.ticks.labelOffset, (isRotated) ? this.top + 12 : this.options.position === "top" ? this.bottom - tl : this.top + tl);
this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1);
this.ctx.font = tickLabelFont;
this.ctx.textAlign = (isRotated) ? "right" : "center";
this.ctx.textBaseline = (isRotated) ? "middle" : this.options.position === "top" ? "bottom" : "top";
this.ctx.fillText(label, 0, 0);
this.ctx.restore();
}
}, xScale);
}
};
}
},
});
Fiddle - http://jsfiddle.net/bh63pe1v/
A simpler solution until this is permanently fixed by the Chart JS contributors is to include a decimal in maxTicksLimit.
For example:
maxTicksLimit: 8,
produces a huge gap at the end.
maxTicksLimit: 8.1,
Does not produce a huge gap at the end.
Depending on what you want to set your maxTicksLimit to, you need to play around with different decimals to see which one produces the best result.
Just do this:
yAxes: [{
ticks: {
stepSize: Math.round((Math.max.apply(Math, myListOfyValues) / 10)/5)*5,
beginAtZero: true,
precision: 0
}
}]
10 = the number of ticks
5 = rounds tick values to the nearest 5 - all y values will be incremented evenly
Similar will work for xAxes too.

How to display pie chart data values of each slice in chart.js

I am using Chart.js for drawing pie chart in my php page.I found tooltip as showing each slice values.
But I wish to display those values like below image.
I do not know how to do this with chart.js.
Please help me.
My Javascript code:
function drawPie(canvasId,data,legend){
var ctx = $("#pie-canvas-" + canvasId).get(0).getContext("2d");
var piedata = [];
$.each(data,function(i,val){
piedata.push({value:val.count,color:val.color,label:val.status});
});
var options =
{
tooltipTemplate: "<%= Math.round(circumference / 6.283 * 100) %>%",
}
var pie = new Chart(ctx).Pie(piedata,options);
if(legend)document.getElementById("legend").innerHTML = pie.generateLegend();
}
php code:
printf('<table><tr>');
echo '<td style="text-align: right;"><canvas id="pie-canvas-'
. $canvasId
. '" width="256" height="256" ></canvas></td><td style="text-align: left;width:360px;height:auto" id="legend" class="chart-legend"></td></tr></table>';
echo '<script type="text/javascript">drawPie('
. $canvasId
. ', '
. $data3
.', '
. $legend
. ');</script>';
For Chart.js 2.0 and up, the Chart object data has changed. For those who are using Chart.js 2.0+, below is an example of using HTML5 Canvas fillText() method to display data value inside of the pie slice. The code works for doughnut chart, too, with the only difference being type: 'pie' versus type: 'doughnut' when creating the chart.
Script:
Javascript
var data = {
datasets: [{
data: [
11,
16,
7,
3,
14
],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
]
};
var pieOptions = {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle)/2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3){ // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var percent = String(Math.round(dataset.data[i]/total*100)) + "%";
//Don't Display If Legend is hide or value is 0
if(dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
}
});
}
}
};
var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pieOptions
});
HTML
<canvas id="pieChart" width=200 height=200></canvas>
jsFiddle
I found an excellent Chart.js plugin that does exactly what you want:
https://github.com/emn178/Chart.PieceLabel.js
From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:
function drawSegmentValues()
{
for(var i=0; i<myPieChart.segments.length; i++)
{
// Default properties for text (size is scaled)
ctx.fillStyle="white";
var textSize = canvas.width/10;
ctx.font= textSize+"px Verdana";
// Get needed variables
var value = myPieChart.segments[i].value;
var startAngle = myPieChart.segments[i].startAngle;
var endAngle = myPieChart.segments[i].endAngle;
var middleAngle = startAngle + ((endAngle - startAngle)/2);
// Compute text location
var posX = (radius/2) * Math.cos(middleAngle) + midX;
var posY = (radius/2) * Math.sin(middleAngle) + midY;
// Text offside to middle of text
var w_offset = ctx.measureText(value).width/2;
var h_offset = textSize/4;
ctx.fillText(value, posX - w_offset, posY + h_offset);
}
}
A Pie Chart has an array of segments stored in PieChart.segments, we can look at the startAngle and endAngle of these segments to determine the angle in between where the text would be middleAngle. Then we would move in that direction by Radius/2 to be in the middle point of the chart in radians.
In the example above some other clean-up operations are done, due to the position of text drawn in fillText() being the top right corner, we need to get some offset values to correct for that. And finally textSize is determined based on the size of the chart itself, the larger the chart the larger the text.
Fiddle Example
With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total value of the items in your dataset, call this totalValue. Then on each segment you can find the percent by doing:
Math.round(myPieChart.segments[i].value/totalValue*100)+'%';
The section here myPieChart.segments[i].value/totalValue is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of 50 and the totalValue was 200. Then the percent that the segment took up would be: 50/200 => 0.25. The rest is to make this look nice. 0.25*100 => 25, then we add a % at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use .toFixed(n) to save decimal places. For example we could do this to save a single decimal place when needed:
var value = myPieChart.segments[i].value/totalValue*100;
if(Math.round(value) !== value)
value = (myPieChart.segments[i].value/totalValue*100).toFixed(1);
value = value + '%';
Fiddle Example of percentile with decimals
Fiddle Example of percentile with integers
You can make use of PieceLabel plugin for Chart.js.
{ pieceLabel: { mode: 'percentage', precision: 2 } }
Demo |
Documentation
The plugin appears to have a new location (and name): Demo Docs.
#Hung Tran's answer works perfect. As an improvement, I would suggest not showing values that are 0. Say you have 5 elements and 2 of them are 0 and rest of them have values, the solution above will show 0 and 0%. It is better to filter that out with a not equal to 0 check!
var val = dataset.data[i];
var percent = String(Math.round(val/total*100)) + "%";
if(val != 0) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
Updated code below:
var data = {
datasets: [{
data: [
11,
16,
7,
3,
14
],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
]
};
var pieOptions = {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle)/2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3){ // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var val = dataset.data[i];
var percent = String(Math.round(val/total*100)) + "%";
if(val != 0) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
}
});
}
}
};
var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pieOptions
});
For Chart.js 3
I've modified "Hung Tran"'s Code.
animation: {
onProgress: function() {
// console.error('this', this);
const ctx = this.ctx;
// ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
let dataSum = 0;
if(this._sortedMetasets.length > 0 && this._sortedMetasets[0].data.length > 0) {
const dataset = this._sortedMetasets[0].data[0].$context.dataset;
dataSum = dataset.data.reduce((p, c) => p + c, 0);
}
if(dataSum <= 0) return;
this._sortedMetasets.forEach(meta => {
meta.data.forEach(metaData => {
const dataset = metaData.$context.dataset;
const datasetIndex = metaData.$context.dataIndex;
const value = dataset.data[datasetIndex];
const percent = (Math.round(value / dataSum * 1000) / 10) + '%';
const mid_radius = metaData.innerRadius + (metaData.outerRadius - metaData.innerRadius) * 0.7;
const start_angle = metaData.startAngle;
const end_angle = metaData.endAngle;
if(start_angle === end_angle) return; // hidden
const mid_angle = start_angle + (end_angle - start_angle) / 2;
const x = mid_radius * Math.cos(mid_angle);
const y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
ctx.fillText(percent, metaData.x + x, metaData.y + y + 15);
});
});
}
}
Give the option for pie chart
onAnimationProgress: drawSegmentValues
like:
var pOptions = {
onAnimationProgress: drawSegmentValues
};
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pOptions
});
Easiest way to do this with Chartjs. Just add below line in options:
pieceLabel: {
fontColor: '#000'
}
Best of luck

Flot Thresholds on x-axis

I created a realtime (updates every 10ms) vertical spline chart using Flot. The chart can be seen here on Codepen. I included the Flot multiple threshold plugin, but I would like for the thresholds to use the x-axis values (on the bottom of the vertical chart) and not the y-axis values (left of the chart). The plot would then paint all values outside of the dashed black lines in red.
In the example you can see that the thresholds use the y-axis to color thresholds (in my case, all values below constraintMax, which is 60).
The operative lines of code are where I set up the options (line 79 in the update function):
var options = {
xaxis: {
position: 'bottom',
min: -10,
max: 100
},
yaxis: {
position: 'left',
min: iterator,
max: updatedData.length-1+iterator,
transform: function (v) { return -v; },
inverseTransform: function (v) { return -v; }
}
};
Where I set up the constraints (line 66 in the update function):
var constraintMax = {
threshold: 60,
color: "rgb(255,0,0)",
evaluate : function(y,threshold){ return y < threshold; }
}
var constraintMin = {
threshold: 25,
color: "rgb(255,0,0)",
evaluate : function(y,threshold){ return y < threshold; }
}
And where I actually plot (line 93 in the update function):
$.plot("#"+elementID, [{data: updatedData, constraints: [constraintMin, constraintMax]}, {data: initialMinData, color: "#000000", dashes: { show: true }}, {data: initialMaxData, color: "#000000", dashes: { show: true }}], options);
Does anyone have any ideas on how to paint the plot points that are outside of the dashed lines red? Thank you in advance.
The multiple threshold plugin only support y-value thresholds out of the box. Therefore you have to change it for your plot. I copied the code into a jsfiddle (I don't like codepen) and changed it there.
1) Your constraintMax threshold is wrong for what you want to do, you need return y > threshold.
2) Changes in the multiple threshold plugin:
if (evaluate(currentPoint[1], threshold)) {
v
if (evaluate(currentPoint[0], threshold)) {
and
function _getPointOnThreshold(threshold, prevP, currP) {
var currentX = currP[0];
var currentY = currP[1];
var prevX = prevP[0];
var prevY = prevP[1];
var slope = (threshold - currentX) / (prevX - currentX);
var yOnConstraintLine = slope * (prevY - currentY) + currentY;
return [threshold, yOnConstraintLine];
}
See the fiddle for the working example.

Remove the tick bar on flot charts

Is it possible to remove the tick bars on the x and y axis on a flot chart?
picture of what I currently have
I want to remove the gray bar between the two series labels
Have you tried to configure your axes like:
xaxis: {
tickLength: 0
}
yaxis: {
tickLength: 0
}
Reference here.
Update in response to your last comment
Since there is no such option one possible workaround could be to color the tickbar the same as your chart background and the ticks like you have it right now.
xaxis: {
color: /* same as your background color */
tickColor: /* different color, like the grayish one you have for the ticks */
}
yaxis: {
color: /* same as your background color */
tickColor: /* different color, like the grayish one you have for the ticks */
}
Hope it helps
I ended up changing the flot source code to allow this to occur.
Here's what I did.
1) added 'tickBar' to the x/yaxis options. (if true, tickBar is shown.. default: true)
2) change the drawGrid function to use this option
drawGrid()
...
//draw the ticks
axes = allAxes();
bw = options.grid.borderWidth;
xBar = (options.xaxis.tickBar !== undefined)? options.xaxis.tickBar:true; //new
yBar = (options.yaxis.tickBar !== undefined)? options.yaxis.tickBar:true; //new
...
if(!axis.innermost){
ctx.strokeStyle = axis.options.color;
ctx.beginPath();
xoff = yoff = 0;
if(axis.direction == "x"){
if(xBar) //new
xoff = plotWidth + 1; // new
} else {
if(yBar) //new
yoff = plotHeight + 1; //new
}
When tickBar is set to false, the offset remains 0 so the line is drawn with a 0 value for width/height so it is not seen.

Categories

Resources