How to remove transparency from bar charts? - ruby

I wonder if there's any way to remove opacity from bar charts built with Chartkick in combination with ChartJS? They always appear semi-transparent, no matter what I do.
This is what I've got so far:
<%=
column_chart(
[
{:data => #invoices},
{:data => #payments}
],
:id => "chart",
:stacked => true,
:colors => ["#E91E63", "#003366"],
:legend => false,
:dataset => {:borderWidth => 0}
)
%>
Thanks for any help.

For two different color with two data-set for proper data comparison Check code snippet
//START Common for all chart
var legend = {
display: true,
position: 'bottom',
labels: {
fontColor: '#000'
}
};
//END Common for all chart
//Dataset
var data1 = {
label: 'Dataset 1',
data: [4, 6, 3, 5, 2, 3],
backgroundColor: 'rgba(255, 99, 132, 1)', //Set 1 for remove transparency
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
};
var data2 = {
label: 'Dataset 2',
data: [5, 2, 3, 4, 6, 3],
backgroundColor: 'rgba(54, 162, 235, 1)', //Set 1 for remove transparency
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
};
var Dataset = [data1, data2]
// Dataset
//START Bar chart
var option = {
scales: {
yAxes: [{
gridLines: {
offsetGridLines: true
},
categorySpacing: 5,
ticks: {
beginAtZero: true
}
}]
},
responsive: true,
//maintainAspectRatio: false,
legend: legend,
//onClick: LoadDataInDetails
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: Dataset
},
options: option
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

OK, it seems that only RGB colours can be passed into column_chart() (correct me if I'm wrong). This is what I ended up with:
<%=
column_chart(
[
{:data => #invoices},
{:data => #payments}
],
:id => "chart",
:stacked => true,
:colors => [to_rgba("#E91E63"), to_rgba("#003366")],
:legend => false,
:dataset => {:borderWidth => 0}
)
%>
module ColorHelper
def to_rgba(hex_value)
opacity = 1
hex_value = hex_value.gsub('#', '')
rgb_values = hex_value.scan(/../).map{ |x| x.hex }
rgb_values << opacity
"rgba(#{rgb_values.join(',')})"
end
end
Not perfect, but it gets the job done.

Related

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');

I want to show project name & hours on chart js using Laravel

I am a beginner at Laravel I am trying to show project name and hours on the chart.js. Unfortunately, data is not showing on the chart; how can I show that?
controller
Chart script
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
#foreach($hour_logs as $key=>$value)
data: {
//labels: ['Red','Purple'],
labels: {{$value}},
datasets: [{
data: {{$value}},
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
#endforeach
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
return response
[
"Joylinkhk: 13,",
"HorizonTechnologies: 2,",
"Alahazrat: 9,",
"j2w: 0,"
]
on the left side project name and on the right side hours
dd($hour_logs)
array:4 [
0 => "Joylinkhk: 13,"
1 => "HorizonTechnologies: 2,"
2 => "Alahazrat: 9,"
3 => "j2w: 0,"
]
When passing complex data structures from PHP to JavaScript you will most likely want to be converting them to JSON.
You can convert arrays to JSON using json_encode(). If you are using Larvel collections, they can be converted using ->toJson().
Use Following code
You must send data from controller by parsing like this
implode(',', $label) and
implode(',', $value)
<script>
let label = {!! $label !!}
let value = {!! $value !!}
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
#foreach($hour_logs as $key=>$value)
data: {
//labels: ['Red','Purple'],
labels: label.split(','),
datasets: [{
data: value.aplit(,),
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
#endforeach
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>

Datepicker and chartjs in Laravel (old chart data when hover)

I have an issue when displaying a chart. I have a function that load data by default for today. After that, I can select a date range. But there is an issue when hovering on labels. They load old chart values and lines. I know that I need to use destroy or update function. But I don't know how to implement it in my code.
Script:
<script type="text/javascript">
$(document).ready(function() {
getdata_chart();
{{-- chartjs --}}
function getdata_chart(start_date='', end_date='')
{
$.ajax({
url: "{{ route('ajaxdata.getdata_chart') }}",
method: "GET",
data:{
start_date:start_date, end_date:end_date
},
success: function(data) {
console.log(data);
var timeFormat = 'DD MMM YYYY г. kk:mm:ss ч.';
var progress = document.getElementById('animationProgress');
var dateANDtime = [];
var Gblok9osx = [];
var Gblok9osy = [];
var Gblok11osx = [];
var Gblok11osy = [];
var Gfilblok10 = [];
var Gfilblok11 = [];
var Gcvn = [];
var Gndk = [];
var Gndk2 = [];
for (var i in data) {
dateANDtime.push(data[i].timestamp);
Gblok9osx.push(data[i].blok9osx);
Gblok9osy.push(data[i].blok9osy);
Gblok11osx.push(data[i].blok11osx);
Gblok11osy.push(data[i].blok11osy);
Gfilblok10.push(data[i].filblok10);
Gfilblok11.push(data[i].filblok11);
Gcvn.push(data[i].cvn);
Gndk.push(data[i].ndk);
Gndk2.push(data[i].ndk2);
}
var chartdata = {
labels: dateANDtime,
datasets: [{
fill: false,
label: 'Отвес блок 9 x',
backgroundColor: 'rgba(199, 228, 238, 0.75)',
borderColor: 'rgba(1, 150, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 0.75)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok9osx,
hidden: false
},
{
fill: false,
label: 'Отвес блок 9 y',
backgroundColor: 'rgba(163, 147, 222, 0.75)',
borderColor: 'rgba(50, 10, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok9osy,
hidden: true
},
{
fill: false,
label: 'Отвес блок 11 x',
backgroundColor: 'rgba(221, 221, 241, 0.75)',
borderColor: 'rgba(100, 100, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok11osx,
hidden: true
},
{
fill: false,
label: 'Отвес блок 11 y',
backgroundColor: 'rgba(147, 227, 227, 0.75)',
borderColor: 'rgba(1, 200, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gblok11osy,
hidden: true
},
{
fill: false,
label: 'Филтрация блок 10',
backgroundColor: 'rgba(139, 105, 132, 0.75)',
borderColor: 'rgba(255, 1, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Gfilblok10,
hidden: true
},
{
fill: false,
label: 'Филтрация блок 11',
backgroundColor: 'rgba(0, 200, 1, 1)',
borderColor: 'rgba(0, 101,1, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gfilblok11,
hidden: true
},
{
fill: false,
label: 'КВН',
backgroundColor: 'rgba(30, 100, 100, 1)',
borderColor: 'rgba(100, 200,1, 0.75)',
hoverBackgroundColor: 'rgba(101, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gcvn,
hidden: true
},
{
fill: false,
label: 'КДК',
backgroundColor: 'rgba(30, 100, 100, 1)',
borderColor: 'rgba(100, 200,1, 0.75)',
hoverBackgroundColor: 'rgba(101, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gndk,
hidden: true
},
{
fill: false,
label: 'НДК',
backgroundColor: 'rgba(30, 100, 100, 1)',
borderColor: 'rgba(100, 200,1, 0.75)',
hoverBackgroundColor: 'rgba(101, 200, 200, 1)',
hoverBorderColor: 'rgba(50, 50, 50, 1)',
data: Gndk2,
hidden: true
}
]
};
$('#reset_zoom').click(function() {
barGraph.resetZoom();
})
$("#save-btn").click(function() {
$("#mycanvas").get(0).toBlob(function(blob) {
saveAs(blob, "chart_1.png");
});
});
var config = {
type: 'line',
data: chartdata,
options: {
responsive: true,
title: {
display: true,
text: 'Диаграма: Отвеси и филтрации'
},
scales: {
yAxes: [{
type: type,
scaleLabel: {
display: true,
labelString: '[ mm ] ,[ m ], [ l/s ]'
},
ticks: {
beginAtZero: false
}
}],
xAxes: [{
type: 'time',
time: {
tooltipFormat: timeFormat,
displayFormats: {
'hour': timeFormat
}
},
scaleLabel: {
display: true,
labelString: 'Дата/Час'
},
ticks: {
beginAtZero: true
}
}]
},
// Container for pan options
pan: {
// Boolean to enable panning
enabled: true,
// Panning directions. Remove the appropriate direction to disable
// Eg. 'y' would only allow panning in the y direction
mode: 'y'
},
// Container for zoom options
zoom: {
// Boolean to enable zooming
enabled: true,
// Zooming directions. Remove the appropriate direction to disable
// Eg. 'y' would only allow zooming in the y direction
mode: 'xy'
},
animation: {
duration: 2000,
onProgress: function(animation) {
progress.value = animation.currentStep / animation.numSteps;
},
onComplete: function() {
window.setTimeout(function() {
progress.value = 0;
}, 2000);
}
},
legend: {
display: true,
labels: {
//fontColor: 'rgb(255, 99, 132)'
usePointStyle: true
}
}
},
plugins: [{
beforeDraw: function(c) {
var reset_zoom = document.getElementById("reset_zoom"); //reset button
var ticks = c.scales['x-axis-0', 'y-axis-0'].ticks.length; //x-axis ticks array
var labels = c.data.labels.length; //labels array
if (ticks < labels) reset_zoom.hidden = false;
else reset_zoom.hidden = true;
}
}]
};
var type = 'linear';
var ctx = document.getElementById("mycanvas");
var barGraph = new Chart(ctx, config);
window.onload = function() {
var ctx = document.getElementById("mycanvas");
window.myLine = barGraph;
};
document.getElementById('toggleScale').addEventListener('click', function() {
type = type === 'linear' ? 'logarithmic' : 'linear';
window.myLine.options.title.text = 'Диаграма('+type+'): Отвеси и филтрации';
window.myLine.options.scales.yAxes[0] = {
display: true,
type: type
};
window.myLine.update();
}); //end data
},
error: function(data) {
console.log(data);
}
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date != '')
{
getdata_chart(start_date, end_date);
}
else
{
alert('Both Date is required');
}
});
});
</script>
in to the controller:
function getdata_chart(Request $request)
{
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
$dateScope = array($start_date, $end_date);
};
$students = otv_fil::whereBetween('timestamp', $dateScope)
->selectRaw('timestamp,blok9osx,blok9osy,blok11osx,blok11osy,filblok10,filblok11,cvn,ndk,ndk - ? as ndk2',[743.38])
->orderBy('timestamp', 'ASC')
->get();
return response()->json($students);
}
The main part need to be in search click function right?

With C3.js, how can I maintain bar width ratio when zooming in?

I have a c3.js bar graph with a subgraph and zooming enabled. I would like for the graph to show more x-tick labels and make the bars a little wider when the user selects a smaller area.
Here's what my graph looks like zoomed out (left) and zoomed in (right):
Here's a fiddle.
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
['x', '2015-01-01', '2015-02-01', '2015-03-01', '2015-04-01', '2015-05-01', '2015-06-01', '2015-07-01', '2015-08-01', '2015-09-01', '2015-10-01', '2015-11-01', '2015-12-01', '2016-01-01', '2016-02-01', '2016-03-01', '2016-04-01', '2016-05-01', '2016-06-01', '2016-07-01', '2016-08-01'],
['y', 100, 200, 300, 200, 100, 450, 800, 900, 12, 70, 500, 450, 20, 100, 200, 300, 200, 100, 450, 800, 900, 12, 70, 500, 450, 20]
],
type: 'bar',
color: function(color, d) {
var color = d3.rgb("#E47911");
if (d.index % 2 == 0) {
color = color.darker(1.2);
}
return color;
}
},
bar: {
width: { ratio: 1.0 }
},
axis: {
x: {
type: 'timeseries',
tick: {
format: "%b",
fit: true
}
},
},
subchart: {
show: true
},
zoom: {
enabled: true
}
});
I'd like it to look more like this when zoomed in:
.
Is there a way to make this happen using C3?
copy the code to your fiddle js panel. type: 'categories' changes the bar scales.
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
['x', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
['y', 100, 200, 300, 200, 100, 450, 800, 900, 12, 70, 500, 450, 20, 100, 200, 300, 200, 100, 450, 800, 900, 12, 70, 500, 450, 20]
],
type: 'bar',
color: function(color, d) {
var color = d3.rgb("#E47911");
if (d.index % 2 == 0) {
color = color.darker(1.2);
}
return color;
}
},
bar: {
width: { ratio: 0.8 }
},
axis: {
x: {
type: 'categories',
tick: {
format: "%b",
fit: true
}
},
},
subchart: {
show: true
},
zoom: {
enabled: true
}
});

Is it possible to have reqular bar and stacked bar in the same jqPlot chart?

I am trying to build a bar chart where 1st series represent the revenue and the next three represent different kind of expenses. So 1st series to be a single bar and the rest three series as stacked bar. Here is my code for the same.
var s0 = [15, 17, 19, 21];
var s1 = [2, 6, 7, 10];
var s2 = [7, 5, 3, 4];
var s3 = [14, 9, 3, 8];
var ticks = ['May', 'June', 'July', 'August'];
var plot3 = $.jqplot('chart1', [s0, s1, s2, s3], {
stackSeries: true,
animate: true,
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
pointLabels: {
show: true,
},
rendererOptions: {
fillToZero: true,
barMargin: 30,
barWidth: 50,
barPadding: 5,
barDirection: 'vertical'
},
},
series: [
{
disableStack: true,
label: 'Revenue'
},
{label: 'Expense1'}, {label: 'Expense2'}, {label: 'Expense3'}
],
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer,
tickOptions: {
fontSize: '13pt'
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
yaxis: {
}
},
legend: {
show: true,
location: 'e',
placement: 'outside'
}
});
I have addded disableStack: true for the first series to exclude it from the stack but the chart still considers it as a part of the stack. Here is the output of my code.
Is there a way to fix this ? Thanks.
Yes. It is the order of the series you pass as argument that is not correct.
BEFORE the stacked series
AFTER the single bar series
and not viceversa...
So you have to move the first series as the last argument...
var plot3 = $.jqplot('chart', [s1, s2, s3, s0], {
and then you need to set the disableStack property on 'true' for the last series...
series: [
{label: 'Expense1'}, {label: 'Expense2'}, {label: 'Expense3',label: 'Revenue', disableStack: true}
],
...and you need to adjust the margins, widts and padding of the columns
as you prefer...

Resources