Google Chart hAxis.gridlines.count does not work as expected - javascript

I have a google Chart with percentage values from 0 to 100% (i.e. 0 to 1)
When I set hAxis.gridlines.count to 10 expecting to get gridlines at 0, 10, 20, ... 90, 100
I get gridlines at 0, 12, 24, 36, ..., 96, 108
I could not find any solution by now.
Here is my Code:
function getData() {
// Create the data table.
var data = new google.visualization.arrayToDataTable([
['Category', 'Fulfillment (%)'],
['A', .75],
['B', .50],
['C', .50],
['D', .30],
['E', 0]
]);
// Set chart options
var options = {
'title': 'My Title',
'height': 300,
'backgroundColor': 'none',
'hAxis': {
'maxValue': 1,
format: '#%',
gridlines: {
count: 10
}
},
'colors': ['#F5821E'],
legend: { position: "none" }
};
var formatter = new google.visualization.NumberFormat({ pattern: '#%' });
formatter.format(data, 1);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Reading the documentation, you can see that hAxis.gridlines.count specifies how many lines to draw, not where to draw them. What you're looking for is probably hAxis.ticks instead.

Use count: 11 and not 10. This will change the labels of the grid lines.

I had the same problem (bug) and I realized that if you set a height for a chart (column chart) then number of horizontal grid will be 2. I you want to use propriety hAxis.gridlines.count than you should to remove height propriety.

Related

set minimum and maximum values for axis' data in highchart

I want to set minimum and maximum values in an axis in highcharts. I have tried min, max, ceiling and floor attributes. They change the range of axis.
Link to the JS Fiddle
yAxis: {
floor: 0,
ceiling: 40,
title: {
text: 'Percentage'
}
},
series: [{
data: [0, 1, -5, 2, 3, 5, 8, 5, 50, 14, 25, 54]
}]
I want the data to be modified automatically based on the minimum/floor and maximum/ceiling values declared in the axis declaration.
For example, if in the above mentioned case, the last and last 4th elements of series should be automatically modified to 40 and the 3rd element to 0.
Is there any attribute of highchart using which I can achieve this without manually checking all the series elements to fall between the min and max values?
No I don't think there is no such a function. Highcharts does not alter your data, it just changes what is displayed. But checking for values beneath or above certain thresholds is really simple:
var data = [0, 1, -5, 2, 3, 5, 8, 5, 50, 14, 25, 54];
var max = 40;
var min = 0;
// clamping "by hand"
console.log( data.map(function(d) { return Math.max(min, Math.min(max, d)); }) );
If you use a library like lodash: these often provide a clamp function so you could write
console.log( _.map(data, function(d) { return _.clamp(d, min, max) }

c3 chart data label overlap issue

I am using C3.js to create a line chart with data labels.
the problem is that some labels overlap when data from 2 lines are very close to each other.
Is there any way to fix this data overlapping issue in C3
var chart = c3.generate({
data: {
labels:true,
columns: [
['data1', 30, 20, 50, 40, 60, 230],
['data2', 40, 130, 90, 240, 130, 220],
['data3', 20, 200, 160, 400, 250, 250]
]
}
});
http://jsfiddle.net/e60o24d0/238/
There are no built-in way to do so.
But you can try to identify and shift problematic labels in labels format function:
labels: {
format: function(v, id, point, line) {
if (point === undefined || line === undefined) return;
var label = d3
.selectAll('.c3-chart-text')
.selectAll('.c3-text')[line][point];
if (...) { // set your condition
var shift = ...; // set your calculation
d3.select(label)
.style('transform', 'translateY(' + shift + 'px)');
}
return v;
}
Some inspiration can be found in your updated fiddle.

Using Chartist.js how do you change the color of the stroke for a donut chart?

Hello I am trying to create the following donut chart using Chartist.js:
GOAL CHART
This is what the chart looks like currently:
Chartist.js Donut Chart
I am trying to find where or how I can change the colors of this chart to match the 1st donut chart. The red and pink seem to be the defaults. I haven't been able to find any documentation of how to accomplish this goal. I would also like to customize the size of the stroke and the size of the chart itself. Any help is greatly appreciated!
Current code:
// ** START CHARTIST DONUT CHART ** //
var chart = new Chartist.Pie('.ct-chart', {
series: [70, 30],
labels: [1, 2]
}, {
donut: true,
showLabel: false
});
chart.on('draw', function(data) {
if(data.type === 'slice') {
// Get the total path length in order to use for dash array animation
var pathLength = data.element._node.getTotalLength();
// Set a dasharray that matches the path length as prerequisite to animate dashoffset
data.element.attr({
'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
});
// Create animation definition while also assigning an ID to the animation for later sync usage
var animationDefinition = {
'stroke-dashoffset': {
id: 'anim' + data.index,
dur: 1000,
from: -pathLength + 'px',
to: '0px',
easing: Chartist.Svg.Easing.easeOutQuint,
// We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
fill: 'freeze'
}
};
// If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
if(data.index !== 0) {
animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
}
// We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
data.element.attr({
'stroke-dashoffset': -pathLength + 'px'
});
// We can't use guided mode as the animations need to rely on setting begin manually
// See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
data.element.animate(animationDefinition, false);
}
});
// ** END CHARTIST DONUT CHART ** //
HTML:
<div class="ct-chart ct-perfect-fourth"></div>
So I figured it out...
I had to go into css and override the defaults. I had to make sure that the css file was loaded after the cdn for Chartist. Then just set width and height of ct-chart.
.ct-series-a .ct-bar, .ct-series-a .ct-line, .ct-series-a .ct-point, .ct-series-a .ct-slice-donut {
stroke: #0CC162;
}
.ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
stroke: #BBBBBB;
}
.ct-chart {
margin: auto;
width: 300px;
height: 300px;
}
Then I had to add donutWidth key to the chart object to set the stroke width:
var chart = new Chartist.Pie('.ct-chart', {
series: [7, 3],
labels: [1, 2]
}, {
donut: true,
donutWidth: 42,
showLabel: false
});
A little later here, but you can provide class names to the data series to allow you to change the colors on each graph independently:
From the docs:
The series property can also be an array of value objects that contain
a value property and a className property to override the CSS class
name for the series group.
Instead of:
series: [70, 30]
Do this:
series: [{value: 70, className: 'foo'}, {value: 30, className: 'bar'}]
and then you can style however you'd like with the stroke css property
Chartist relies on modifying CSS to control the colors, sizes, etc. of the charts.
I'd suggest having a look at the documentation here to learn lots of cool tips and tricks: https://gionkunz.github.io/chartist-js/getting-started.html
But to your specific question, here's an except from the above link that tells you how to control the donut chart:
/* Donut charts get built from Pie charts but with a fundamentally difference in the drawing approach. The donut is drawn using arc strokes for maximum freedom in styling */
.ct-series-a .ct-slice-donut {
/* give the donut slice a custom colour */
stroke: blue;
/* customize stroke width of the donut slices in CSS. Note that this property is already set in JavaScript and label positioning also relies on this. In the right situation though it can be very useful to style this property. You need to use !important to override the style attribute */
stroke-width: 5px !important;
/* create modern looking rounded donut charts */
stroke-linecap: round;
}
I've managed to change the stroke color by overriding this class. You can change ct-series-b to which bar graph you change to change color (ct-series-a, ct-series-b and etc).
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.css" />
<style>
.ct-series-b .ct-bar, .ct-series-b .ct-line, .ct-series-b .ct-point, .ct-series-b .ct-slice-donut {
stroke: goldenrod;
}
</style>
</head>
<body>
<div class="ct-chart ct-perfect-fourth"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartist/0.10.1/chartist.min.js"></script>
<script>
window.onload = function() {
var data = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
series: [
[5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8],
[3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4]
]
};
var options = {
seriesBarDistance: 10
};
var responsiveOptions = [
['screen and (max-width: 640px)', {
seriesBarDistance: 5,
axisX: {
labelInterpolationFnc: function (value) {
return value[0];
}
}
}]
];
new Chartist.Bar('.ct-chart', data, options, responsiveOptions);
}
</script>
</body>
</html>
What I did to make it work is the following. I am using a bar chart, but I guess it is the same for all graphs.
my css
.ct-chart .ct-series.stroke-green .ct-bar {
stroke: green;
}
.ct-chart .ct-series.stroke-yellow .ct-bar {
stroke: rgba(255, 167, 38, 0.8);
}
.ct-chart .ct-series.stroke-red .ct-bar {
stroke: rgba(230, 20, 20, 0.8);
}
chart conf
{
labels: ['Jan', 'Feb'],
series: [
{className:"stroke-green", meta:"OK", data: [12,23] },
{className:"stroke-yellow", meta:"Rest", data: [34,34]},
{className:"stroke-red", meta: "NOK", data: [2, 5] },
]
}
This code worked for me to change the color of the stroke:
// Prepare chart params
var chartColors = ['orange'];
var chartWidth = 9;
var percent = 77;
var arc = percent ? 360 * percent / 100 : 0;
// Create chart
var chart = new Chartist.Pie('.my-donut', {
series: [arc],
labels: [percent + '%'],
}, {
donut: true,
donutWidth: chartWidth,
startAngle: 0,
total: 360,
});
// Set chart color
chart.on('draw', function(data) {
if(data.type === 'slice') {
if (chartColors[data.index]) {
data.element._node.setAttribute('style','stroke: ' + chartColors[data.index] + '; stroke-width: ' + chartWidth + 'px');
}
}
});
Bar charts with a single serie - use nth-child(N):
.ct-bar:nth-child(1){
stroke: #379683 !important;
}
.ct-bar:nth-child(2){
stroke: #91A453 !important;
}
.ct-bar:nth-child(3){
stroke: #EFB200 !important;
}
The answers above wont work for me since I'm dynamically excluding categories with 0 points. You can do it pragmatically though. You can directly modify the svg node. My charts use fill instead of stroke but the method should be the same. This worked for me in Chrome:
const data = {
series: [],
labels: []
};
const pieColors = [];
enrollment.CoverageLevelTotals.forEach(e => {
if (e.Total === 0) return;
data.series.push(e.Total);
data.labels.push(e.Total);
pieColors.push(colors[e.CoverageLevel]);
});
new Chartist.Pie(document.getElementById(canvasId), data,
{
width: '160px',
height: '160px',
donut: true,
donutWidth: 50,
donutSolid: true,
showLabel: (data.series.length > 1)
}).on('draw',function (data) {
if (data.type !== 'slice') return;
data.element._node.setAttribute('style','fill:' + pieColors[data.index]);
});
}

How to add custom labels in donut renderer jqplot?

I want to add dataLabels labels for s1 donut and dataLabels percent or no label for s2.How can i do that?
function drawDonut(chartId){
var s1 = [['a',6], ['b',8], ['c',14], ['d',20]];
var s2 = [['e', 6], ['f', 8], ['g', 14], ['h', 20]];
var plot = $.jqplot(chartId,[s1,s2], {
seriesDefaults: {
// make this a donut chart.
renderer:$.jqplot.DonutRenderer,
rendererOptions:{
// Donut's can be cut into slices like pies.
sliceMargin: 0,
dataLabelThreshold: 0,
// Pies and donuts can start at any arbitrary angle.
startAngle: -90,
showDataLabels: true,
// By default, data labels show the percentage of the donut/pie.
// You can show the data 'value' or data 'label' instead.
dataLabels: 'label'
}
}
}
That's because you're setting showDataLabels in seriesDefaults. Check out http://www.jqplot.com/docs/files/jqPlotOptions-txt.html for how to set options per series.

Flot charts - How to plot only 1 tick per month on x-axis?

I want to have 1 tick on the x-axis every month.
I have this setting in flot charts, but it sometimes only plots 1 tick in the x-axis every 2 months
var options = {
xaxis: { mode: "time", timeformat: "%m/%d/%y", minTickSize: [1, "month"] }
};
If you want full control over the ticks on an axis you can set the ticks property with an array, for example:
var tickArray = [ new Date(2013, 0, 1).getTime(), new Date(2013, 1, 1).getTime(), ... ];
var options = {
xaxis: { mode: "time", timeformat: "%m/%d/%y", ticks: tickArray }
};
You can use tickSize property to set 1 month on x-axis like this.
tickSize: [1, "month"]

Categories

Resources