I want to make this Javascript function more efficient? - javascript

I have three pie charts being generated using Google Charts API. I want to compress this function further as there is a lot of duplication. Is there a loop I can make for it etc.
if (data) {
var myVar = [];
var myVar1 = [];
var myVar2 = [];
myVar.push(['Label', 'Value']);
myVar1.push(['Label', 'Value']);
myVar2.push(['Label', 'Value']);
myVar.push(['Car Sales Today', data.salesToday, ]);
myVar1.push(['Car Sales Yesterday', data.salesYesterday]);
myVar2.push(['Car Sales Last Week', data.salesLastWeek]);
var build1 = {
package: 'PieChart',
data: myVar,
customTooltips: [
data.salesToday,
],
container: 'today-sales-chart',
options: {
width: 'auto',
height: 300,
chartArea: { width: '50%', height: '80%' },
yAxis: { textPosition: 'none' },
legend: { position: "bottom" },
tooltip: { isHtml: true },
colors: ['#e6dc39'],
pieSliceText: 'none'
}
};
var build2 = {
package: 'PieChart',
data: myVar1,
customTooltips: [
data.salesYesterday,
],
container: 'yesterday-sales-chart',
options: {
width: 'auto',
height: 300,
chartArea: { width: '50%', height: '80%' },
yAxis: { textPosition: 'none' },
legend: { position: "bottom" },
tooltip: { isHtml: true },
colors: ['#33bb18'],
pieSliceText: 'none'
}
};
var build3 = {
package: 'PieChart',
data: myVar2,
customTooltips: [
data.salesLastWeek
],
container: 'lastweek-sales-chart',
options: {
width: 'auto',
height: 300,
chartArea: { width: '50%', height: '80%' },
yAxis: { textPosition: 'none' },
legend: { position: "bottom" },
tooltip: { isHtml: true },
colors: ['#e06e29'],
pieSliceText: 'none'
}
};
charts.push(build1, build2, build3);
google.setOnLoadCallback.drawCharts(build1.container);
google.setOnLoadCallback.drawCharts(build2.container);
google.setOnLoadCallback.drawCharts(build3.container);
}
I tried to do the following for example:
var myVar, myVar1, myVar2 = [];
but I get an error. Any help would be great.

I took some time to optimize your code, but I didn't test it. make sure all the variable names are ok, and don't make a conflict on your code
if (data) {
var allData = [{
arr : [['Label', 'Value'], ['Car Sales Today', data.salesToday]],
container : 'today-sales-chart',
customTooltips: data.salesToday
}
,{
arr : [['Label', 'Value'], ['Car Sales Yesterday', data.salesYesterday]],
container : 'yesterday-sales-chart',
customTooltips: data.salesYesterday
}
,{
arr : [['Label', 'Value'], ['Car Sales Last Week', data.salesLastWeek]],
container : 'lastweek-sales-chart',
customTooltips: data.salesLastWeek
}
];
var options = {
width: 'auto',
height: 300,
chartArea: { width: '50%', height: '80%' },
yAxis: { textPosition: 'none' },
legend: { position: "bottom" },
tooltip: { isHtml: true },
colors: ['#e6dc39'],
pieSliceText: 'none'
}
var builds = [];
for (var index in allData) {
builds.push({
package: 'PieChart',
data: allData[index].arr,
customTooltips: [ allData[index].customTooltips ],
container: allData[index].container,
options: options
});
}
for(var index in builds) {
charts.push(builds[index]);
google.setOnLoadCallback.drawCharts(builds[index].container);
}
}
Update
to add the possibility to change the color, in this case you don't need to use options as an independent variable :
var builds = [];
for (var index in allData) {
builds.push({
package: 'PieChart',
data: allData[index].arr,
customTooltips: [ allData[index].customTooltips ],
container: allData[index].container,
options: {
width: 'auto',
height: 300,
chartArea: { width: '50%', height: '80%' },
yAxis: { textPosition: 'none' },
legend: { position: "bottom" },
tooltip: { isHtml: true },
colors: allData[index].color, // <--- you set the color here
pieSliceText: 'none'
}
});
}

Related

Google chart horizontal date bars too wide

My issue is that the each bar spans a few days either side of the date instead of just the one day on the hAxis (x axis). How do I make each hAxis bar be just 1 day wide?
google.charts.safeLoad({'packages':['corechart']});
google.charts.setOnLoadCallback(function(){
chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
});
...
var rows = [[new Date("2022-12-14 00:00:00"),2,"14/12/2022","color:blue"],[new Date("2022-12-01 00:00:00"),1,"01/12/2022","color:blue"],[new Date("2022-09-21 00:00:00"),1,"21/09/2022","color:blue"],[new Date("2022-03-16 00:00:00"),1,"16/03/2022","color:blue"]];
var data = new google.visualization.DataTable();
data.addColumn('date', "Date");
data.addColumn('number', "Quantity");
data.addColumn({type:"string", role:"tooltip"});
data.addColumn({type:"string", role:"style"});
data.addRows(rows);
var options = {
hAxis:{
title: "Date",
textStyle : { fontSize:10 },
titleTextStyle: { fontSize:12, bold:true, italic:false },
viewWindow: { min:new Date("2021-12-14"), max:new Date("2022-12-14") }
},
vAxis:{
title: "Quantity",
textStyle : { fontSize:10 },
titleTextStyle: { fontSize:12, bold:true, italic:false },
format:"0"
},
isStacked: "absolute",
animation: {
duration: 750,
easing: "out",
startup: true
},
chartArea: {
width: "92%",
height: "160",
top: "4"
},
explorer: { actions: ["dragToZoom", "rightClickToReset"] },
legend: {position: 'none'},
width: "100%",
height: "100%",
bar: {
gap:2,
groupWidth: "95%"
}
};
chart.draw(data, options);

How to add text on every section edges in funnel highcharts

With help of my previous question, I'm able to set equal heights for all the sections to the funnel. How can I add some extra texts to the edges(right) of every section. I did not find any documentation for this. My expected funnel chart as follows:
Highcharts.chart('container', {
chart: {
type: 'funnel'
},
title: {
text: 'Sales funnel'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '<b>{point.name}</b> ({point.y:,.0f})',
softConnector: true,
inside: true,
},
neckHeight: "0%",
neckWidth: "80%",
width: '15%',
reversed: true,
}
},
legend: {
enabled: false
},
series: [{
name: 'Unique users',
data: [
['Website visits', 15654],
['Downloads', 4064],
['Requested price list', 1987],
['Invoice sent', 976],
['Finalized', 846]
]
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
plotOptions: {
series: {
dataLabels: {
inside: true
},
center: ['50%', '50%'],
width: '100%'
}
}
}
}]
}
});
jsfiddle Example: https://jsfiddle.net/kiranuk/xhfbyj64/
Thanks for the help.
For adding extra text on the chart use Highcharts. SVGRenderer
API Reference:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer
Sample code:
chart: {
type: 'funnel',
events: {
render: function() {
let chart = this,
point1 = chart.series[0].points[4],
x = point1.dlBox.x + point1.dlBox.bottomWidth + chart.plotLeft + 1,
y = point1.dlBox.y + chart.plotTop - point1.dlBox.height;
if (!chart.myCustomText) {
chart.myCustomText = chart.renderer
.text('1% <br> Did')
.css({
fontSize: '10px',
zIndex: '3px'
})
.add();
}
//pdate text coordinates
chart.myCustomText.attr({
x: x,
y: y
})
}
}
},
Demo:
https://jsfiddle.net/BlackLabel/kLyt6ngs/

Google bar chart won't be transparent background

I use these codes but I couldn't make transparent background. Also, I couldn't make loop for data. I tried loop by using data.addColumn(ar[i],ar2[i]) but it wouldn't be succeed.
function drawPaLoChart() {
var data = google.visualization.arrayToDataTable([
['Hours', 'Seconds'],
['0', pageload[0]],
['1', pageload[1]],
['21', pageload[21]],
['22', pageload[22]],
['23', pageload[23]]
]);
var options = {
chart: {
legend: { position: 'none' },
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
axes: {
x: {
0: { side: 'top', label: 'White to move'} // Top x-axis.
}
},
bar: { groupWidth: "90%" },
backgroundColor: {fill: 'transparent'},
chartArea: {
backgroundColor: 'transparent'
}
}
};
var chart = new google.charts.Bar(document.getElementById('palochart'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
first, only the title and subtitle options should be inside the chart key,
as follows...
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
legend: { position: 'none' },
axes: {
x: {
0: { side: 'top', label: 'White to move'} // Top x-axis.
}
},
bar: { groupWidth: "90%" },
backgroundColor: {fill: 'transparent'},
chartArea: {
backgroundColor: 'transparent'
}
};
as for the loop, use an array to build the data in a loop...
var chartData = [
['Hours', 'Seconds']
];
for (var i = 0; i < pageload.length; i++) {
chartData.push([i.toString(), pageload[i]]);
}
var data = google.visualization.arrayToDataTable(chartData);

Echart icon in series tooltip

So i have the following configuration:
const frequencyChartoption = {
title: {},
tooltip: {},
legend: {
data: ['Frekvens', 'Vigtighed']
},
xAxis: {
type: 'category',
data: ['marker_01', 'marker_02'],
axisLabel: {
formatter: function (value) {
return '{' + value + '| }\n{value|}';
},
margin: 20,
rich: {
value: {
lineHeight: 30,
align: 'center'
},
marker_01: {
height: 20,
align: 'center',
backgroundColor: {
image: icons.marker_01
}
},
marker_02: {
height: 20,
align: 'center',
backgroundColor: {
image: icons.maker_02
}
},
}
}
},
yAxis: {},
series: [{
name: 'Frekvens',
type: 'bar',
data: frequencyChartFrequencyScore,
tooltip: icons.marker_01,
itemStyle: {
normal: {
color: colors[0],
label: {
interval: 5,
show: true,
position: 'top',
formatter: '\n{c}'
}
}
}
},
{
name: 'Vigtighed',
type: 'bar',
data: frequencyChartImportance,
itemStyle: {
normal: {
color: colors[1],
label: {
show: true,
position: 'top',
formatter: '\n{c}'
}
}
}
}
]
};
Now as you can see i am using two images as my xAxis
Now i wish to make these show up on my tooltip when i hover over the chart. However i am not quite sure how to do that and was hoping some of you might be able to help?
Simply stated, a series may have a tooltip but the tooltip must be listed as an object with an identifying trigger (see tooltip documentation).
series: [{
name: 'Frekvens',
type: 'bar',
data: frequencyChartFrequencyScore,
tooltip: {
show: true,
trigger: 'axis',
formatter: (params) => {
// see tooltip.formatter for details
// you want to focus on the 'marker' property
return params[0].name;
}
}
}]
With this in mind, you can set two variables and print them as need be within the output of your tooltip. See the additional example below (from CodePen).
var myChart = echarts.init(document.getElementById("main"));
// specify chart configuration item and data
var option = {
title: {
text: "ECharts entry example"
},
tooltip: {
show: true,
trigger: "axis",
backgroundColor: 'rgba(0, 0, 0, 0.8)',
formatter: (params) => {
// create new marker
var icon0 = `<span data-tooltip="minimum" style="border-left: 2px solid #fff;display: inline-block;height: 12px;margin-right: 5px;width: 20px;"><span style="background-color:${params[0].color};display: block;height: 4px;margin-top: 4px;width: 20px;"></span></span>`;
var icon1 = `<span data-tooltip="implied-high" style="background-color:rgba(255,255,255,.75);border-radius: 2px;display: inline-block;height: 12px;margin-right:5px;width: 20px;"><span style="background-color:${params[0].color};border: 1px solid ${params[0].color};border-radius:50%;display:block;height:6px;margin-left:7px;margin-top:3px;width:6px;"></span></span>`;
console.log("params", params, params[0].name);
return `${icon0} ${params[0].name}
${icon1} ${params[0].value}`;
},
textStyle: {
fontWeight: 'bold',
fontSize: 18
}
},
legend: {
data: ["Sales"]
},
xAxis: {
data: ["shirt", "cardign", "chiffon shirt", "pants", "heels", "socks"]
},
yAxis: {},
series: [
{
name: "Sales",
type: "bar",
data: [5, 20, 36, 10, 10, 20]
}
]
};
// use configuration item and data specified to show chart
myChart.setOption(option);

google charts dashed line between interpolateNulls

I use Google Charts Line chart and have implement interpolateNulls = true. This works great but now I want the line that interpolateNulls draws to be dotted.
Is it possible to set lineDashStyle: [4,4] just on the interpolateNulls?
Here is some of my code:
var drawChart = function (data, type, firstIsAverage, vAxisHeader) {
var shift = (firstIsAverage === true) ? 0 : 1;
var fontname = 'Roboto';
var fontsize = 14;
var chartObject = {
type: type,
display: false,
data: data,
options: {
chartArea: {
left: 100,
top: 30,
width: 800,
height: 240
},
vAxis: {
title: vAxisHeader,
titleTextStyle: {
italic: false
}
},
// lineDashStyle: [4, 4], //Just want this on the interpolateNulls
interpolateNulls: true, //Here is the interpolate
fontName: fontname,
fontSize: fontsize,
legend: 'none',
colors: colors.slice(shift),
isStacked: "true",
fill: 20,
displayExactValues: false
},
formatters: {}
};
setAllColumnsVisible(chartObject);
return chartObject;
};

Categories

Resources