google piechart pie background image - image

I am using google charts and here is my piechart code...I want to use background repeating image instead of colors. Is that possible with google charts?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 1],
['Eat', 1],
['Commute', 1],
['Watch TV', 1],
['Sleep', 1]
]);
var options = {
pieSliceBorderColor : 'none',
chartArea:{left:5,top:5,width:390,height:390},
enableInteractivity:false,
pieStartAngle:30,
pieHole: 0.6,
slices: {
0: { color: 'brown', offset: 0.01 },
1: { color: 'brown', offset: 0.01 },
2: { color: 'brown', offset: 0.01 },
3: { color: 'brown', offset: 0.01 },
4: { color: 'brown', offset: 0.01 },
}
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
options.slices[sliceCount].color = 'transparent';
chart.draw(data, options);
}

there are no standard options to fill slices with repeating image
however, you can modify the chart's svg after it finishes drawing
on the 'ready' event,
create an image pattern and add to svg defs
then replace the 'fill' attribute on the chart elements that should have the image
pie chart slices are typically drawn with <path> elements
when there is only one slice (100%), a <rect> element is used
the legend is drawn with <circle>
keep in mind, if you need to create an image of the chart,
custom modifications such as these will not work when using method --> getImageURI
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 1],
['Eat', 1],
['Commute', 1],
['Watch TV', 1],
['Sleep', 1]
]);
var options = {
pieSliceBorderColor: 'none',
pieSliceText: 'none',
chartArea: {
bottom: 12,
left: 12,
top: 12,
width: 390,
height:390
},
enableInteractivity: false,
pieStartAngle: 30,
pieHole: 0.6,
slices: {
0: { color: 'brown', offset: 0.1 },
1: { color: 'brown', offset: 0.1 },
2: { color: 'brown', offset: 0.1 },
3: { color: 'brown', offset: 0.1 },
4: { color: 'brown', offset: 0.1 },
}
};
var container = $('#piechart')[0];
var chart = new google.visualization.PieChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
// create image pattern
var svgNS = $('svg')[0].namespaceURI;
var pattern = document.createElementNS(svgNS, 'pattern');
pattern.setAttribute('id', 'whiteHat');
pattern.setAttribute('patternUnits', 'userSpaceOnUse');
pattern.setAttribute('width', 16);
pattern.setAttribute('height', 16);
var image = document.createElementNS(svgNS, 'image');
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://findicons.com/files/icons/512/star_wars/16/clone_old.png');
image.setAttribute('x', 0);
image.setAttribute('y', 0);
image.setAttribute('width', 16);
image.setAttribute('height', 16);
pattern.appendChild(image);
$('#defs')[0].appendChild(pattern);
// add image to pie slices
$('svg path').attr('fill', 'url(#whiteHat)');
// add image to legend circles
$('svg circle').attr('fill', 'url(#whiteHat)');
// test chart image
$(container.parentNode).append('<img alt="Chart" src="' + chart.getImageURI() + '">');
});
chart.draw(data, options);
}
div {
padding: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>piechart</div>
<div id="piechart"></div>
<div>image</div>

Related

am chart 5 Stacked column chart with line chart

I am trying to create a stacked column chart and trying to integrate a line chart on Y axis, Chart is rendering but line is not visible which is using opposite y axis value.
latitudeSeries should create a line chart using the opposite y axis that is Y axis value on the right side. But it's not rendering the line chart though opposite y axis is rendered.
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<!-- Chart code -->
<script>
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
layout: root.verticalLayout
}));
// Add legend
// https://www.amcharts.com/docs/v5/charts/xy-chart/legend-xy-series/
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.p50,
x: am5.p50
}));
var data = [{
"year": "2021",
"europe": 2.5,
"namerica": 2.5,
"asia": 2.1,
"lamerica": 1,
"meast": 0.8,
"africa": 0.4,
"latitude": 40.00
}, {
"year": "2022",
"europe": 2.6,
"namerica": 2.7,
"asia": 2.2,
"lamerica": 0.5,
"meast": 0.4,
"africa": 0.3,
"latitude": 45.74
}, {
"year": "2023",
"europe": 2.8,
"namerica": 2.9,
"asia": 2.4,
"lamerica": 0.3,
"meast": 0.9,
"africa": 0.5,
"latitude": 39.74
}];
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
categoryField: "year",
renderer: am5xy.AxisRendererX.new(root, {
cellStartLocation: 0.1,
cellEndLocation: 0.9
}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
min: 0,
renderer: am5xy.AxisRendererY.new(root, {})
}));
var latitudeAxisRenderer = am5xy.AxisRendererY.new(root, {opposite:true});
var latitudeAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: latitudeAxisRenderer
}));
var latitudeSeries = chart.series.push(am5xy.LineSeries.new(root, {
xAxis: xAxis,
yAxis: latitudeAxis,
valueYField: "latitude",
valueXField: "year",
tooltip:am5.Tooltip.new(root, {
labelText:"latitude: {valueY}"
})
}));
latitudeSeries.strokes.template.setAll({ strokeWidth: 2 });
// Add circle bullet
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
latitudeSeries.bullets.push(function() {
var graphics = am5.Circle.new(root, {
strokeWidth: 2,
radius: 5,
stroke: latitudeSeries.get("stroke"),
fill: root.interfaceColors.get("background"),
});
graphics.adapters.add("radius", function(radius, target) {
return target.dataItem.dataContext.townSize;
})
return am5.Bullet.new(root, {
sprite: graphics
});
});
latitudeSeries.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
function makeSeries(name, fieldName, stacked) {
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
stacked: stacked,
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: fieldName,
categoryXField: "year"
}));
series.columns.template.setAll({
tooltipText: "{name}, {categoryX}:{valueY}",
width: am5.percent(90),
tooltipY: am5.percent(10)
});
xAxis.data.setAll(data);
series.data.setAll(data);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear();
series.bullets.push(function () {
return am5.Bullet.new(root, {
locationY: 0.5,
sprite: am5.Label.new(root, {
text: "{valueY}",
fill: root.interfaceColors.get("alternativeText"),
centerY: am5.percent(50),
centerX: am5.percent(50),
populateText: true
})
});
});
legend.data.push(series);
}
makeSeries("Europe", "europe", true);
makeSeries("North America", "namerica", true);
makeSeries("Asia", "asia", true);
makeSeries("Latin America", "lamerica", true);
makeSeries("Middle East", "meast", true);
makeSeries("Africa", "africa", true);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
chart.appear(1000, 100);
}); // end am5.ready()
</script>
<!-- HTML -->
<div id="chartdiv"></div>
Your xAxis is a category axis, not a value axis. Thus, in your latitudeSeries settings, you must use categoryXField instead of valueXField.
For more readability, I recommend you to synchronize latitudeAxis and yAxis using syncWithAxis. You should also set transparency on your column series.
I edited your code and added these little corrections (with comments).
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<!-- Chart code -->
<script>
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
layout: root.verticalLayout
}));
// Add legend
// https://www.amcharts.com/docs/v5/charts/xy-chart/legend-xy-series/
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.p50,
x: am5.p50
}));
var data = [{
"year": "2021",
"europe": 2.5,
"namerica": 2.5,
"asia": 2.1,
"lamerica": 1,
"meast": 0.8,
"africa": 0.4,
"latitude": 40.00
}, {
"year": "2022",
"europe": 2.6,
"namerica": 2.7,
"asia": 2.2,
"lamerica": 0.5,
"meast": 0.4,
"africa": 0.3,
"latitude": 45.74
}, {
"year": "2023",
"europe": 2.8,
"namerica": 2.9,
"asia": 2.4,
"lamerica": 0.3,
"meast": 0.9,
"africa": 0.5,
"latitude": 39.74
}];
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
categoryField: "year",
renderer: am5xy.AxisRendererX.new(root, {
cellStartLocation: 0.1,
cellEndLocation: 0.9
}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
min: 0,
renderer: am5xy.AxisRendererY.new(root, {})
}));
var latitudeAxisRenderer = am5xy.AxisRendererY.new(root, {opposite:true});
var latitudeAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
syncWithAxis: yAxis, // Synchronize axes to get a more readable grid
renderer: latitudeAxisRenderer
}));
var latitudeSeries = chart.series.push(am5xy.LineSeries.new(root, {
xAxis: xAxis,
yAxis: latitudeAxis,
valueYField: "latitude",
categoryXField: "year", // Use categoryXField instead of valueXField
tooltip:am5.Tooltip.new(root, {
labelText:"latitude: {valueY}"
})
}));
latitudeSeries.strokes.template.setAll({ strokeWidth: 2 });
// Add circle bullet
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/#Bullets
latitudeSeries.bullets.push(function() {
var graphics = am5.Circle.new(root, {
strokeWidth: 2,
radius: 5,
stroke: latitudeSeries.get("stroke"),
fill: root.interfaceColors.get("background"),
});
graphics.adapters.add("radius", function(radius, target) {
return target.dataItem.dataContext.townSize;
})
return am5.Bullet.new(root, {
sprite: graphics
});
});
latitudeSeries.data.setAll(data);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
function makeSeries(name, fieldName, stacked) {
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
stacked: stacked,
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueYField: fieldName,
categoryXField: "year"
}));
series.columns.template.setAll({
tooltipText: "{name}, {categoryX}:{valueY}",
width: am5.percent(90),
tooltipY: am5.percent(10),
// Set column and stroke transparency for more readability
opacity: 0.75,
stroke: "transparent"
});
xAxis.data.setAll(data);
series.data.setAll(data);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear();
series.bullets.push(function () {
return am5.Bullet.new(root, {
locationY: 0.5,
sprite: am5.Label.new(root, {
text: "{valueY}",
fill: root.interfaceColors.get("alternativeText"),
centerY: am5.percent(50),
centerX: am5.percent(50),
populateText: true
})
});
});
legend.data.push(series);
}
makeSeries("Europe", "europe", true);
makeSeries("North America", "namerica", true);
makeSeries("Asia", "asia", true);
makeSeries("Latin America", "lamerica", true);
makeSeries("Middle East", "meast", true);
makeSeries("Africa", "africa", true);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
chart.appear(1000, 100);
}); // end am5.ready()
</script>
<!-- HTML -->
<div id="chartdiv"></div>

Amcharts to display only even numbers in Y-axis

I am trying to have only even numbers from 0 and up on the Y-axis of a amcharts5 Line chart but i cannot figure it out how to.
Example: if the biggest value is 5 my Y-axis should how: 0, 2, 4, 6.
Is it possible to achieve this?
What I'm currently having:
var yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
min: 0,
maxPrecision: 0,
maxDeviation: 0.1,
renderer: am5xy.AxisRendererY.new(root, {})
})
);
Result:
What I need to achieve:
Have you tried to play with the minGridDistance property referenced here?
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {
minGridDistance: 20
})
}));
Full example:
am5.ready(function () {
var root = am5.Root.new("chartdiv");
var chart = root.container.children.push(am5xy.XYChart.new(root, {}));
var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererX.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {
minGridDistance: 20 // Play with it and see what happens...
})
}));
var series = chart.series.push(am5xy.LineSeries.new(root, {
name: "Series",
xAxis: xAxis,
yAxis: yAxis,
valueXField: "valueX",
valueYField: "valueY"
}));
var data = [],
valueX = 0,
valueY = 0;
for (var i = 0; i < 20; i++) {
data.push({ valueX: i, valueY: i });
}
series.data.setAll(data);
});
#chartdiv {
width: 100%;
height: 350px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<div id="chartdiv"></div>

How to create gauge diagram with amchart 5 with arabic text in it

I want to create a gauge diagram with amcharts 5 with persian text on it. All the code sample I found is working correctly with english text on it. But when I want to use persian or arabic text (rtl languages), it doesn't show texts correct. How can I solve this problem?
Here is my code:
<script>
var root = am5.Root.new("chartdiv");
root.setThemes([
am5themes_Animated.new(root)
]);
var chart = root.container.children.push(am5radar.RadarChart.new(root, {
panX: false,
panY: false,
startAngle: 160,
endAngle: 380
}));
var axisRenderer = am5radar.AxisRendererCircular.new(root, {
innerRadius: -40
});
axisRenderer.grid.template.setAll({
stroke: root.interfaceColors.get("background"),
visible: true,
strokeOpacity: 0.8
});
var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation: 0,
min: -40,
max: 100,
strictMinMax: true,
renderer: axisRenderer
}));
var axisDataItem = xAxis.makeDataItem({});
var clockHand = am5radar.ClockHand.new(root, {
pinRadius: am5.percent(20),
radius: am5.percent(100),
bottomWidth: 40
})
var bullet = axisDataItem.set("bullet", am5xy.AxisBullet.new(root, {
sprite: clockHand
}));
xAxis.createAxisRange(axisDataItem);
var label = chart.radarContainer.children.push(am5.Label.new(root, {
fill: am5.color(0xffffff),
centerX: am5.percent(50),
textAlign: "center",
centerY: am5.percent(50),
fontSize: "3em"
}));
axisDataItem.set("value", 50);
bullet.get("sprite").on("rotation", function () {
var value = axisDataItem.get("value");
var text = Math.round(axisDataItem.get("value")).toString();
var fill = am5.color(0x000000);
xAxis.axisRanges.each(function (axisRange) {
if (value >= axisRange.get("value") && value <= axisRange.get("endValue")) {
fill = axisRange.get("axisFill").get("fill");
}
})
label.set("text", Math.round(value).toString());
clockHand.pin.animate({ key: "fill", to: fill, duration: 500, easing: am5.ease.out(am5.ease.cubic) })
clockHand.hand.animate({ key: "fill", to: fill, duration: 500, easing: am5.ease.out(am5.ease.cubic) })
});
var i = 0;
var a = setInterval(function() {
if (i === 9) {
axisDataItem.animate({
key: "value",
to: Math.round(28),
duration: 100,
easing: am5.ease.out(am5.ease.cubic)
});
}
else if (i === 25) {
clearInterval(a);
}
else {
axisDataItem.animate({
key: "value",
to: Math.round(Math.random() * 140 - 40),
duration: 2000,
easing: am5.ease.out(am5.ease.cubic)
});
i++;
}
}
, 100);
var bandsData = [{
title: "لاغری مفرط",
direction: "rtl",
position: "right",
orientation: "rtl",
color: "#ee1f25",
lowScore: -40,
highScore: -20
}, {
title: 'لاغر',
color: "#f04922",
lowScore: -20,
highScore: 0
}, {
title: "نرمال",
color: "#fdae19",
lowScore: 0,
highScore: 20
}, {
title: "اضافه وزن",
color: "#f3eb0c",
lowScore: 20,
highScore: 40
}, {
title: "چاق",
color: "#b0d136",
lowScore: 40,
highScore: 60
}, {
title: "چاقی زیاد",
color: "#54b947",
lowScore: 60,
highScore: 80
}, {
title: "چاقی مفرط",
color: "#0f9747",
lowScore: 80,
highScore: 100
}];
am5.array.each(bandsData, function (data) {
var axisRange = xAxis.createAxisRange(xAxis.makeDataItem({}));
axisRange.setAll({
value: data.lowScore,
endValue: data.highScore
});
axisRange.get("axisFill").setAll({
visible: true,
fill: am5.color(data.color),
fillOpacity: 0.8
});
axisRange.get("label").setAll({
text: data.title,
inside: true,
radius: 15,
fontSize: "0.9em",
fill: root.interfaceColors.get("background")
});
});
chart.rtl = true;
chart.appear(1000, 100);
chart.rtl = true;
</script>
Final result is like this image:
amcharts5 result
I also searched about it in documentation of amcharts 5 but I couldn't find the answer.

How to hide/show bars differentiate by a colors and by click on labels, using chartjs bar charts?

I am using chartjs to show one month attendance data, what I want to acheive is to show each day data with different colors like Present, absent and leave. I want labels on top and by click on that label user should be able to hide/show that particular label data, below is my code.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- HTML -->
<canvas id="chartJsDiv"></canvas>
<script>
function attendanceSummaryChart3(attendence)
{
var datasets = [];
var labels_data = [];
var num_of_hour = [];
var bar_colours = [];
var border_colr = [];
var real_data_count = attendence.length;
for (var i = 0; i < real_data_count; i++) {
var mydate = new Date(attendence[i].date);
var month = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"][mydate.getMonth()];
var str = mydate.getDate() + ' ' +month;
labels_data.push(str);
if(parseFloat(attendence[i].hours.replace(':','.')) < 6.00)
{
if(attendence[i].is_leave != null)
{
var applied_leave_type = attendence[i].is_leave_applied.leave_type.slug;
if(applied_leave_type == "work-from-home")
{
// Full hours in case work from home
num_of_hour.push('9');
bar_colours.push('RGB(25, 135, 84)');
border_colr.push('rgba(3, 126, 25, 0.85)');
// creating datasets
datasets.push({label: 'Work From Home', data: '9', backgroundColor: 'RGB(25, 135, 84)' });
}
else
{
// Leave applied
if(parseFloat(attendence[i].hours.replace(':','.')) == 0)
{
num_of_hour.push('-9');
bar_colours.push('RGB(25, 135, 84)');
border_colr.push('rgba(14, 8, 191, 0.8)');
// creating datasets
datasets.push({label: 'On Leave', data: '-9', backgroundColor: 'RGB(25, 135, 84)'});
}
else
{
num_of_hour.push(parseFloat(attendence[i].hours.replace(':','.')));
bar_colours.push('RGB(25, 135, 84)');
border_colr.push('rgba(14, 8, 191, 0.8)');
// creating datasets
datasets.push({label: 'Half Leave', data: parseFloat(attendence[i].hours.replace(':','.')), backgroundColor: 'RGB(25, 135, 84)'});
}
}
}
else
{
if(parseFloat(attendence[i].hours.replace(':','.')) == 0)
{
// If absent and no leave is applied
num_of_hour.push('-9');
bar_colours.push('RGB(255, 0, 0)');
border_colr.push('rgba(6, 108, 166, 0.8)');
// creating datasets
datasets.push({label: 'Absent (No Leave Applied)', data: '-9', backgroundColor: 'RGB(255, 0, 0)' });
}
else
{
// If present and didn't complete 06 hours in office
num_of_hour.push(parseFloat(attendence[i].hours.replace(':','.')));
bar_colours.push('RGB(255, 0, 0)');
border_colr.push('rgba(255, 99, 132, 1)');
// creating datasets
datasets.push({label: 'Present (Half Time)', data: parseFloat(attendence[i].hours.replace(':','.')), backgroundColor: 'RGB(255, 0, 0)' });
}
}
}
else
{
// Full hours
num_of_hour.push(parseFloat(attendence[i].hours.replace(':','.')));
bar_colours.push('RGB(0, 255, 0)');
border_colr.push('rgba(75, 192, 192, 1)');
// creating datasets
datasets.push({label: 'Present', data: parseFloat(attendence[i].hours.replace(':','.')), backgroundColor: 'RGB(25, 135, 84)' });
}
}
console.log(datasets);
const ctx = document.getElementById('chartJsDiv').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels_data,
datasets: [
{
label: ['Attendence'],
data: num_of_hour,
backgroundColor: bar_colours,
borderColor: border_colr,
}
]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
},
});
}
</script>
I am attaching a screenshot below currently I only have one label but I want multiple labels based on multiple colors bar
You need to use a second dataset to achieve this:
Then you can fill null values in both datasets where you dont use the values of that dataset, so null values on the places where value is negative in positive dataset and vice versa in other one.
Then you can use the property skipNull to make it so the bars dont take up space:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, null, 3, 5, null, 3],
backgroundColor: 'green'
},
{
label: '# of Points',
data: [null, -11, null, null, -3, null],
backgroundColor: 'red'
}
]
},
options: {
skipNull: true
}
}
const 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.7.1/chart.js"></script>
</body>
should be this part
label: ['Attendence', 'newLabel', 'xxx'],
under
const ctx = document.getElementById('chartJsDiv').getContext('2d');

Aligning C3 line shapes with Bar charts

We have the following mixed line chart / bar chart in C3:
a bar chart with two groups (light/dark blue is one group, gray is the
other group)
two other data sets represented as line with stroke-width = 0 that represent the limit for group1 and group2.
How can we place the circle shape for line1 aligned with the bar for group1 and the circle shape for line2 aligned with the two bars of group2?
In the following example, we basically would want one of the two circles to be moved slightly to the right so to align with the center of a group and the other one slightly to the left.
var chartSettings = {
padding: {
left: 120,
right: 120
},
bindto: '#chart',
data: {
x: 'Dates',
type: 'bar',
types: {
line1: 'line',
line2: 'line'
},
groups: [
['data2', 'data3'],
],
colors: {
data1: '#f3e274',
data2: '#85bdde',
data3: '#ccebfb'
},
},
bar: {
width: {
ratio: 0.50
}
},
point: {
r: 8
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%d-%m-%Y'
}
},
y: {
label: { // ADD
text: '',
position: 'outer-middle'
},
},
}
};
var date1 = new Date(2015, 1, 1, 0,0, 0,0);
var date2 = new Date(2015, 3, 1, 0,0, 0,0);
var date3 = new Date(2015, 6, 1, 0,0, 0,0);
var xAxis = ['Dates', date1, date2,date3];
var line1 = ['line1', 50, 60,55];
var line2 = ['line2', 70, 75,60];
var data1 = ['data1', 40, 35,30];
var data2 = ['data2', 5, 10,10];
var data3 = ['data3', 20, 15,30];
chartSettings.data.columns = [xAxis,
line1,
line2,
data1,
data2,
data3];
c3.generate(chartSettings);
#cr-chart .c3-line-accordatoTotale {
stroke-width: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.11/c3.min.js"></script>
<div id="chart"/>
var chartSettings = {
bindto: '#chart',
data: {
x: 'Dates',
type: 'bar',
types: {
line1: 'line',
line2: 'line'
},
groups: [
['data2', 'data3'],
],
names: {
line1: 'Limit for data1',
line2: 'Limit for data2 + data3',
data1: 'Data1',
data2: 'Data2',
data3: 'Data3'
},
},
bar: {
width: {
ratio: 0.50 // this makes bar width 50% of length between ticks
}
},
point: {
r: 8
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%d-%m-%Y'
}
},
y: {
label: { // ADD
text: '',
position: 'outer-middle'
}
},
}
};
var date1 = new Date(2016, 1, 1, 0, 0, 0, 0);
var date2 = new Date(2016, 3, 1, 0, 0, 0, 0);
var date3 = new Date(2016, 6, 1, 0, 0, 0, 0);
var xAxis = ['Dates',date1,date2,date3];
var line1 = ['line1', 50, 70,80];
var data1 = ['data1', 30, 40, 60];
var line2 = ['line2', 70, 60,40];
var data2 = ['data2',10,15,20];
var data3 = ['data3',15,30,5];
chartSettings.data.columns = [xAxis,
line1,
line2,
data1,
data2,
data3];
c3.generate(chartSettings);
#chart .c3-line-line1 {
stroke-width: 0px;
}
#chart .c3-line-line2 {
stroke-width: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.11/c3.min.js"></script>
<div id="chart"/>
It would be nice if you attached some jsfiddle.
But at this point I can say that you probably need to look inside .c3-chart-lines container and find desired line eighter by order:
.c3-chart-line:first-child // or last-child?
or by data name:
.c3-chart-line.c3-target-YOUR-ORANGE-DATA-NAME
Hope this helps.

Resources