highcharts: dynamically define colors in pie chart - javascript

I'm trying to dynamically define color for each seria depending of their type.
Below is my code which doesn't work but showing what I'm trying to do. I would like to define colour for certain type eg:
if type = 'IS' then color = '#FFCACA'
I cannot expect that ret will have all types so I need to know which types are returned in ret and then asociate color to certain type.
How to do that?
this is code since data received:
success: function (ret) {
$(function () {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'divPie_' + id,
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: true,
width: 350,
height: 350
},
title: {
text: refrigname
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Current selection',
color: (function () {
switch (ret.type) {
case 'AB': return '#C6F9D2';
case 'BC': return '#CCCCB3';
case 'CL': return '#CECEFF';
case 'CI': return '#FFCAFF';
case 'HB': return '#D0CCCD';
case 'ON': return '#FFCC99';
case 'PM': return '#FFCBB9';
case 'SR': return '#EAEC93';
case 'TS': return '#D7FBE6';
case 'IS': return '#FFCACA';
case 'FREE': return '#00FF00';
}
}),
data: (function () {
var arr = [];
$(ret).each(function () {
var labelname = "";
switch (this.type) {
case "AB": labelname = "Antibodies"; break;
case "BC": labelname = "Bacteria"; break;
case "CL": labelname = "Cell lines"; break;
case "CI": labelname = "Custom items"; break;
case "HB": labelname = "Hybridoma"; break;
case "ON": labelname = "Oligonucleotides"; break;
case "PM": labelname = "Plasmids"; break;
case "SR": labelname = "siRNA"; break;
case "TS": labelname = "Tissue samples"; break;
case "IS": labelname = "Isolates"; break;
case "FREE": labelname = "Free space"; break;
}
arr.push([labelname, this.cnt]);
})
return arr;
})()
}]
});
});
});
}

For a pie chart you have to set the slice color inside data.
And you have to use the point name and not serie type, serie type will always be "pie".
For this you can use javascript object notation to store which color each serie will have.
It's fastar than use a switch.
var getColor = {
'AB': '#C6F9D2',
'BC': '#CCCCB3',
'CL': '#CECEFF',
'CI': '#FFCAFF',
'HB': '#D0CCCD',
'ON': '#FFCC99',
'PM': '#FFCBB9',
'SR': '#EAEC93',
'TS': '#D7FBE6',
'IS': '#FFCACA',
'FREE': '#00FF00'
};
series: [{
type: 'pie',
name: 'Current selection',
data: [
{
name: 'AB',
y: 45.0,
color: getColor['AB']
}, {
name: 'BC',
y: 26.8,
color: getColor['BC']
}, {
name: 'CL',
y: 12.8,
sliced: true,
selected: true,
color: getColor['CL']
}, {
name: 'CI',
y: 8.5,
color: getColor['CI']
}, {
name: 'HB',
y: 6.2,
color: getColor['HB']
}, {
name: 'ON',
y: 0.7,
color: getColor['ON']
}
]
}]
You can see it working here.

The return statement you have there is returning from the function being passed to the each function, not the color function. Also, there's no need to use a switch case for this in JavaScript.
EDIT: Try something like this
series: [{
type: 'pie',
name: 'Current selection',
color: {
'AB': '#C6F9D2',
'BC': '#CCCCB3',
'CL': '#CECEFF',
'CI': '#FFCAFF',
'HB': '#D0CCCD',
'ON': '#FFCC99',
'PM': '#FFCBB9',
'SR': '#EAEC93',
'TS': '#D7FBE6',
'IS': '#FFCACA',
'FREE': '#00FF00'
}[this.type]
}]
It's not really clear from your code what ret is, so I'm not sure the above code works, but it should give you a rough idea of how it can be done.

Why not set the color property when you push the data series to the chart? Without seeing what you are using to build your series object I can only provide some psuedo-code:
for each seriesItem in seriesList (
set highcharts.series[seriesItem].name = seriesList[seriesItem].seriesTitle
set highcharts.series[seriesItem].data = seriesList[seriesItem].data
set highcharts.series[seriesItem].Note = seriesList[seriesItem].extraInfo
set highcharts.series[seriesItem].color = switch (seriesList[seriesItem].type) {
case 'AB': return '#C6F9D2';
case 'BC': return '#CCCCB3';
case 'CL': return '#CECEFF';
case 'CI': return '#FFCAFF';
case 'HB': return '#D0CCCD';
case 'ON': return '#FFCC99';
case 'PM': return '#FFCBB9';
case 'SR': return '#EAEC93';
case 'TS': return '#D7FBE6';
case 'IS': return '#FFCACA';
case 'FREE': return '#00FF00';
}
)
Essentially you preprocess the data series elements. See this question for explicit formatting. You can set the color property of a series - you do not have to depend on the default HighCharts color list or a custom color list as described in another answer. Note that the color property is not listed in the HighCharts API reference but you can use it.

I use Highcharts without giving any color property as it is using their own library for auto select color. Use below, hope it will work for u
series: [{
type: 'pie',
name: 'Current selection',
data: [
['Name_1', 537],
['Name_2', 181],
['Name_3', 156]
]
}]
we can set highchart custom color by setOption function
Highcharts.setOptions({
colors: ['#F64A16', '#0ECDFD', '#FFF000']
});

Related

Insert data into table while adding nodes of FamilyTree

hope you all will be fine (sorry for my bad English),
I am making a FamilyTree in Oracle apex using PL/SQL Dynamic Content following this example this. Here multiple nodes can be made but the problem is that actually I want to add Node's Data into database table ,How can I do It,
Here is my code
declare
Begin
Htp.p('
<script src="https://balkan.app/js/FamilyTree.js"></script>
<div id="tree"/>
<script>
//JavaScript
FamilyTree.templates.tommy.nodeCircleMenuButton = FamilyTree.templates.tommy_female.nodeCircleMenuButton = FamilyTree.templates.tommy_male.nodeCircleMenuButton = {
radius: 25,
x: 230,
y: 60,
color: ''#fff'',
stroke: ''#aeaeae''
};
var family = new FamilyTree(document.getElementById("tree"), {
nodeBinding: {
field_0: "name"
},
nodeCircleMenu: {
editNode: {
icon: FamilyTree.icon.edit(30, 30, ''#aeaeae''),
text: "Edit node",
color: "white"
},
},
});
family.nodeCircleMenuUI.on(''show'', function (sender, args) {
var node = family.getNode(args.nodeId);
if (FamilyTree.isNEU(node.mid)) {
args.menu.husband = {
icon: FamilyTree.icon.husband(30, 30, ''#F57C00''),
text: "Add partner",
color: "white"
};
}
if (FamilyTree.isNEU(node.fid)) {
args.menu.father = {
icon: FamilyTree.icon.father(30, 30, ''#039BE5''),
text: "Add Head",
color: "white"
};
}
});
family.nodeCircleMenuUI.on(''click'', function (sender, args) {
var node = family.getNode(args.nodeId);
switch (args.menuItemName) {
case "husband":
family.addPartnerNode({ gender: ''male'', pids: [args.nodeId] });
break;
case "wife":
family.addPartnerNode({ gender: ''female'', pids: [args.nodeId] });
break;
case "pet":
family.addPartnerNode({ gender: ''pet'', pids: [args.nodeId] });
break;
case "mother":
var data = { gender: ''female'' };
if (!FamilyTree.isNEU(node.fid)) {
data.pids = [node.fid];
}
family.addParentNode(args.nodeId, ''mid'', data);
break;
case "father":
var data = { gender: ''male'' };
if (!FamilyTree.isNEU(node.mid)) {
data.pids = [node.mid];
}
family.addParentNode(args.nodeId, ''fid'', data);
break;
case "editNode": family.editUI.show(args.nodeId);
break;
default:
};
});family.load([
]);</script>');end;
I am totally new programmer ,
You need to use the event listeners "add" and "update":
https://balkan.app/FamilyTreeJS/API/classes/FamilyTree#on-1
You can also see some server isde examples for Org Chart JS (it is almost the same):
https://balkan.app/OrgChartJS/Docs/GitHub

JavaScript - iterating through an array for checking condition

I am creating a high charts graph that I would like to dynamically give the graph color to depending on the title of an object. I currently have an array graphData that has an object title.
I have 5 possible results of titles:
"LOW", "MEDIUM-LOW", "MEDIUM", "MEDIUM-HIGH", AND "HIGH"
I am now attempting to iterate through my array and assign a color depending on what title the index has.
My entire graph receives one color based off the last title of the array. I would like the color to effect each index of the array seperartely.
For example: if "MEDIUM-HIGH" is the last title in the array, my entire graph gets #DD5F0C
Here is my code:
Array:
graphData: [ […]
​
0: Object { title: "LOW", result: 62582 }
​
1: Object { title: "MEDIUM-LOW", result: 57758 }
​
2: Object { title: "LOW", result: 8795 }
​
3: Object { title: "HIGH", result: 262525 }
​
4: Object { title: "MEDIUM-HIGH", result: 167168 } ]
let graphColor = ""
for (i = 0; i < graphData.length; i++) {
if (graphData[i].title === "LOW") {
graphColor = "#0D6302"
} else if (graphData[i].title === "MEDIUM-LOW") {
graphColor = "#0B7070"
} else if (graphData[i].title === "MEDIUM") {
graphColor = "#DC9603"
} else if (graphData[i].title === "MEDIUM-HIGH") {
graphColor = "#DD5F0C"
} else if (graphData[i].title === "HIGH") {
graphColor = "#C50710"
}
}
HighCharts code :
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: "Bar Graph"
},
xAxis: {
},
yAxis: {
min: 0,
formatter: function() {
return this.value + "%";
},
title: {
text: '% of Total'
}
},
legend: {
reversed: false
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: `graphData[0].title`,
color: graphColor,
data: [graphData[0]],
}, {
name: 'graphData[1].title',
color: graphColor,
data: [graphData[1]],
showInLegend: false,
linkedTo: ":previous"
}, {
name: 'graphData[2].title,
color: graphData[0].title,
data: [graphData[2]]
}, {
name: graphData[3].title,
color: '#DC9603',
data: [graphData[3]]
}, {
name: graphData[4].title,
color: graphColor,
data: [graphData[4]]
}, {
name: graphData[5].title,
color: graphColor,
data: [graphData[5]]
}]
});
I am expecting my "color" to be dynamically generated based off of what graphData.title equals for that specific index.
You are having trouble because you have graphData.length number of entries, but only one graphColor variable to hold the color. Your code samples don't look complete so I'll make some assumptions about how the surrounding code must be. I recommend building up your series data in the for-loop directly so you can just use it in the Highcharts.chart call. The code is easier to read that way and probably more flexible too if you need to have more data rows.
// build the series data array here so it's simple to use in the chart call
const series = new Array(graphData.length);
for (let i = 0; i < graphData.length; i++) {
let graphColor = "#000000"; // a default color just in case
// can use if/else or a switch here
if (graphData[i].title === "LOW") {
graphColor = "#0D6302";
} else if (graphData[i].title === "MEDIUM-LOW") {
graphColor = "#0B7070";
} else if (graphData[i].title === "MEDIUM") {
graphColor = "#DC9603";
} else if (graphData[i].title === "MEDIUM-HIGH") {
graphColor = "#DD5F0C";
} else if (graphData[i].title === "HIGH") {
graphColor = "#C50710";
}
series[i] = {
name: graphData[i].title,
color: graphColor,
data: [graphData[i].result]
};
}
// Adjust the series data as needed
series[1].showInLegend = false;
series[1].linkedTo = ":previous";
Highcharts.chart("container", {
chart: { type: "bar" },
title: { text: "Bar Graph" },
xAxis: {},
yAxis: {
min: 0,
formatter: function() {
return this.value + "%";
},
title: { text: "% of Total" }
},
legend: { reversed: false },
plotOptions: { series: { stacking: "normal" } },
series: series
});
Not sure if I've properly understood what are you trying to do, but try this way:
const colorMap = { "LOW":"#0D6302",
"MEDIUM-LOW": "#0B7070",
"MEDIUM": "#DC9603",
"MEDIUM-HIGH": "#DD5F0C",
"HIGH":"#C50710"
}
...
series: [{
name: `graphData[0].title`,
color: colorMap[graphData[0].title],
data: [graphData[0]],
}, {
In the Highchart way - you can iterate through the series after chart initialization and set the wanted colors by particular series.
Demo: https://jsfiddle.net/BlackLabel/6hm4ebna/
chart: {
type: 'bar',
events: {
load() {
let chart = this;
chart.series.forEach(s => {
console.log(s)
if (s.name === 'test1') {
s.update({
color: 'red'
})
}
else if (s.name === 'test3') {
s.update({
color: 'green'
})
}
})
}
}
},
API: https://api.highcharts.com/highcharts/chart.events.load
If this wouldn't help please reproduce your attempt with the sample data on the online editor which I could work on.

Trying to display different types of charts using select/option tag

// Vancouver Population
var ctx = document.getElementById("lineChart");
var lineChart = new Chart(ctx, {
type:'line',
data: {
labels: ["2000", "2005", "2010", "2015", "2018"],
datasets: [{
label: 'Vancouver Population Data',
data: [195000,2093000,2278000,2485000,2597000],
borderColor: [
'rgba(255,99,132,1)'
],
backgroundColor:['rgba(255,200,200,0.3)'],
borderWidth: 1,
//borderDash:([3]),
pointBackgroundColor:"red",
pointBorderColor: "rgba(250,10,10,0.1)",
pointBorderWidth:"10",
pointStyle:"rectRounded",
pointHoverBackgroundColor:"rgba(255,0,0,0.5)",
pointHoverBorderColor: "rgba(255,255,100,0.7)",
pointHoverRadius:"10",
//showLine:false,
//steppedLine:"false"
}]
},
options: {
title:{
display:true,
text:"Populations in Vancouver",
fontSize:20,
fontColor:"rgba(20,20,20,1)"
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000'
},
},
elements:{
line:{
tension:0, //disables bezier curves
}
},
scales: {
yAxes:[{
ticks: {
beginAtZero:true,
callback: function(value,index,values){
return value + " people"
}
}
}]
},
/*animation: {
duration:0, // general animation time
},*/
hover:{
animationDuration:0, // duration of animations when hovering an item
},
responsiveAnimationDuration:0, // animation duration after a resize
}
});
// Vancouver Precipitation
var ctx = document.getElementById("barChart");
var BarChart = new Chart(ctx, {
type:'bar',
data: {
labels:["May 2017", "June 2017", "July 2017", "Aug 2017","Sep 2017","Oct 2017","Nov 2017","Dec 2017","Jan 2018","Feb 2018","Mar 2018","Apr 2018","May 2018"],
datasets:[{
label:"Precipitation Data",
data:[102.2,46.4,1.8,5.0,29.4,114.8,197.0,170.6,249.4,105.8,111.8,134.8,1.4],
backgroundColor: [
'rgba(255,99,132,0.5)',
'rgba(155,130,32,0.5)',
'rgba(105,9,132,0.5)',
'rgba(15,130,202,0.5)',
'rgba(15,250,252,0.5)',
'rgba(205,100,32,0.5)',
'rgba(0,205,0,0.5)',
'rgba(55,15,52,0.5)',
'rgba(255,0,0,0.5)',
'rgba(25,59,52,0.5)',
'rgba(0,100,55,0.5)',
'rgba(200,111,199,0.5)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(155,130,32,1)',
'rgba(105,9,132,1)',
'rgba(15,130,202,1)',
'rgba(15,250,252,1)',
'rgba(205,100,32,0.5)',
'rgba(0,205,0,1)',
'rgba(55,15,52,1)',
'rgba(255,0,0,1)',
'rgba(25,59,52,1)',
'rgba(0,100,55,1)',
'rgba(200,111,199,1)',
],
borderWidth:"1",
pointHoverBackgroundColor:"#fff",
hoverBorderColor:"#fff",
}]
},
options: {
title:{
display:true,
text:"Vancouver Precipitation",
fontSize:20,
fontColor:"rgba(10,0,20,0.9)"
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000'
}
},
scales:{
yAxes:[{
ticks:{
beginAtZero:true,
callback: function(value,index,values){
return value + " mm"
}
}
}]
}
},
});
// Ethnicity
var ctx = document.getElementById("pieChart");
var PieChart = new Chart(ctx,{
type:'pie',
data:{
labels:['European Candadian','Chinese','South Asia','Fillipino','Southeast Asian','Japanese','Latin American','Mixed visible minority','Korean','Aboriginal','West Asian','Black','Arab'],
datasets:[{
label:"Ethnicity",
data:[46.2,27.7,6,6,3,1.7,1.6,1.5,1.5,2,1.2,1,0.5],
backgroundColor: [
'rgba(255,99,132,0.5)',
'rgba(155,130,32,0.5)',
'rgba(105,9,132,0.5)',
'rgba(15,130,202,0.5)',
'rgba(15,250,252,0.5)',
'rgba(205,100,32,0.5)',
'rgba(0,205,0,0.5)',
'rgba(55,15,52,0.5)',
'rgba(255,0,0,0.5)',
'rgba(25,59,52,0.5)',
'rgba(0,100,55,0.5)',
'rgba(200,231,50,0.5)',
'rgba(155,22,30,0.5)',
],
borderColor:[
'rgba(255,99,132,0.5)',
'rgba(155,130,32,0.5)',
'rgba(105,9,132,0.5)',
'rgba(15,130,202,0.5)',
'rgba(15,250,252,0.5)',
'rgba(205,100,32,0.5)',
'rgba(0,205,0,0.5)',
'rgba(55,15,52,0.5)',
'rgba(255,0,0,0.5)',
'rgba(25,59,52,0.5)',
'rgba(0,100,55,0.5)',
'rgba(200,231,50,0.5)',
'rgba(155,22,30,0.5)',
],
borderWidth:[1]
}],
cutoutPercentage:[0]
},
options:{
title:{
display:true,
text:"Vancouver Ethnicity",
fontSize:"20",
fontColor:"rgba(20,20,20,1)"
},
}
});
// Radar
Chart.defaults.scale.ticks.beginAtZero = true;
var ctx = document.getElementById("radarChart");
var RadarChart = new Chart(ctx, {
type:'radar',
data:{
labels:['Hiking','Sporting Events','Stanley Park','Skiing & Snowboarding','Beaches','eating'],
datasets:[{
label:"Male",
data:['50','70','80','60','20','70'],
backgroundColor:[
'rgba(255,155,32,0.5)',
],
borderWidth:1,
pointBackgroundColor:["yellow","black","green","white","skyblue","red"],
pointHoverBackgroundColor:["black"],
pointStyle:["triangle"]
},
{
label:"Female",
data:['60','30','80','20','50','60'],
backgroundColor:[
'rgba(155,15,132,0.5)',
],
borderWidth:1,
pointBackgroundColor:["yellow","black","green","white","skyblue","red"],
pointHoverBackgroundColor:["black"],
pointStyle:["triangle"]
}
]
},
options:{
title:{
display:true,
text:"Activities in Vancouver",
fontSize:"20",
fontColor:"rgba(10,0,20,0.9)"
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000',
}
},
scales:{
scale: {
}
}
}
});
// Select Options
var lineChart = document.getElementById("lineChart"),
barChart = document.getElementById("barChart"),
pieChart = document.getElementById("pieChart"),
radarChart = document.getElementById("radarChart");
function myFunction(){
var chartType = document.getElementById("chartType");
var i = chartType.selectedIndex;
if (chartType.options[i]) {
lineChart.style.display = "inherit";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<div class="container">
<h1><span>V</span>ancouver Census</h1>
<!-- Vancouver Population -->
<select id="chartType" onchange="myFunction()">
<option value="line">Population</option>
<option value="bar">Precipitation</option>
<option value="pie">Ethnicity</option>
<option value="radar">Activity</option>
</select>
<div class="chart_container" id="display">
<canvas id="lineChart" style="display:none"></canvas>
<canvas id="barChart" style="display:none"></canvas>
<canvas id="pieChart" style="display:none"></canvas>
<canvas id="radarChart" style="display:none"></canvas>
</div>
</div>
What I am trying to achieve here is when I select the "population", the linechart shows up. And when I select "precipitation", barChart shows up.
I am aware that I am missing some kind of logical functions. I tried with if statement by writing if (chartType.options[0]) {lineChart.style.display = "inherit"} but it ends up applying to all the options. I appreciate for tips and help.
Following my comment:
1- Hide the previously shown chart
In order to do that, you have two things to do: find what chart is currently being displayed, and hide it.
Let's first add two classes: hidden-chart and active-chart and their CSS:
.hidden-chart { display: none !important; }
.active-chart { display: inherit !important; }
And edit the HTML accordingly:
<canvas id="lineChart" class="hidden-chart"></canvas>
<canvas id="barChart" class="hidden-chart"></canvas>
<canvas id="pieChart" class="hidden-chart"></canvas>
<canvas id="radarChart" class="hidden-chart"></canvas>
Okay, so now you can have two types of charts: hidden charts with the hidden-chart class and the currently being displayed chart with active-chart class.
In order to achieve 1), you'd now have to add the following code to your function:
function myFunction() {
const currentChart = document.querySelector("#display .active-chart");
if (currentChart) {
currentChart.classList.remove("active-chart"); // Remove the active-chart class
currentChart.classList.add("hidden-chart"); // Add the hidden-chart class thus hiding the chart
}
var chartType = document.getElementById("chartType");
var i = chartType.selectedIndex;
if (chartType.options[i]) {
lineChart.style.display = "inherit";
}
}
2- A switch case on the selected option's text:
Well that is a quite trivial switch, on the HTMLElement.text variable:
function myFunction() {
const currentChart = document.querySelector("#display .active-chart");
if (currentChart) {
currentChart.classList.remove("active-chart"); // Remove the active-chart class
currentChart.classList.add("hidden-chart"); // Add the hidden-chart class thus hiding the chart
}
var chartType = document.getElementById("chartType");
var i = chartType.selectedIndex;
const selectedOption = chartType.options[i]; // The option the user has clicked on
let toEnableChart;
switch (selectedOption.text) {
case 'Population':
toEnableChart = lineChart;
break;
case 'Precipitation':
toEnableChart = barChart;
break;
case 'Ethnicity':
toEnableChart = pieChart;
break;
case 'Activity':
toEnableChart = radarChart;
break;
}
if (chartType.options[i]) {
lineChart.style.display = "inherit";
}
}
You could replace the switch with a standard if else if else if else construct.
3- Enable the new chart
Now that we know what chart to display (toEnableChart variable, thanks to the switch ; and we know how to display it - remember our hidden-chart and active-chart classes?), it's time to display it!
function myFunction() {
const currentChart = document.querySelector("#display .active-chart");
if (currentChart) {
currentChart.classList.remove("active-chart"); // Remove the active-chart class
currentChart.classList.add("hidden-chart"); // Add the hidden-chart class thus hiding the chart
}
var chartType = document.getElementById("chartType");
var i = chartType.selectedIndex;
const selectedOption = chartType.options[i]; // The option the user has clicked on
let toEnableChart;
switch (selectedOption.text) {
case 'Population':
toEnableChart = lineChart;
break;
case 'Precipitation':
toEnableChart = barChart;
break;
case 'Ethnicity':
toEnableChart = pieChart;
break;
case 'Activity':
toEnableChart = radarChart;
break;
}
if (toEnableChart) {
toEnableChart.classList.remove("hidden-chart");
toEnableChart.classList.add("active-chart");
}
As you may notice, displaying the new chart is step #1, but backwards.
Feel free to comment if something is unclear.

How to pass variable in a variable in JavaScript?

I want to define a variable that contains a variable. In this example the variable that I want to pass is "filldata".
I have tried passing it using $filldata as well as +filldata+.
if (fill == true) {
$filldata = "fill: true,";
} else {
$filldata = "fill: false,";
};
if (amount == true) {
var set1 = {
label: "Earnings",
id: "earnings",
data: data1,
points: {
show: true,
},
bars: {
show: false,
barWidth: 12,
aling: 'center'
},
lines: {
show: true,
$filldata
},
yaxis: 1
};
} else {
var set1 = "";
}
Since you are just trying to create a boolean property named 'fill' with the value of some variable, also called fill (using fussy truthy/falsy values), then you can just skip creating the intermediate $filldata variable altogether and just create the property with the value evaluated inline. It's more succinct and more obvious.
Try:
if (amount == true) {
var set1 = {
label: "Earnings",
id: "earnings",
data: data1,
points: {
show: true,
},
bars: {
show: false,
barWidth: 12,
aling: 'center'
},
lines: {
show: true,
fill: fill==true
},
yaxis: 1
};
} else {
var set1 = "";
}
EDIT:
Also, note that it is not good practice to declare the variable set1 inside the if block scope if you intend to use it elsewhere. A better alternative would be:
var set1 = (amount == true) ?
{...your object as defined above...}
: "";

Highcharts visualize, style series

I'm using Highcharts.visualize to draw the graph from a table containing the data.
You can test my working code here: http://jsfiddle.net/S2XM8/1/
I have two questions:
I want to have a separate styling for my "Additional value". How do I go about it?
Can I add data for the X-axis via the javascript? For example if I need to fill in the gap between 2014-05-27 and 2014-05-25 in the table.
Highcharts.visualize = function (table, options, tableClass) {
// the categories
options.xAxis.categories = [];
$('tbody th', table).each( function () {
options.xAxis.categories.push(this.innerHTML);
});
// the data series
options.series = [];
$('tr', table).each( function (i) {
var tr = this;
$('.graph', tr).each( function (j) {
if (i === 0) { // get the name and init the series
options.series[j] = {
name: this.innerHTML,
data: []
};
} else { // add values
options.series[j].data.push(parseFloat(this.innerHTML));
console.log(this.innerHTML);
}
});
});
options.title = { text: 'Some graph' };
$('#' + tableClass + '-graph').highcharts(options);
};
var tableNumber = document.getElementById('rank-table'),
options = {
chart: {
zoomType: 'x'
},
xAxis: {
tickInterval: 30,
reversed: true,
labels: {
rotation: 45
},
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Rank'
},
min: 1,
reversed: true
},
legend: {
layout: 'vertical',
align: 'middle',
verticalAlign: 'bottom',
borderWidth: 0
}
};
Highcharts.visualize(tableNumber, options, 'number');
Both things are possible, but require to modify visualize method, see: http://jsfiddle.net/S2XM8/4/
You can set series options in a chart and then merge with data:
series: [{
// nothing special
}, {
type: 'column' // set series type for example
}]
And merging:
options.series[j] = options.series[j] || {};
options.series[j].name = this.innerHTML,
options.series[j].data = [];
Check parsed value before passing as point value:
var value = parseFloat(this.innerHTML);
if(isNaN(value)) { //null value - produces NaN when parsing
options.series[j].data.push(10);
} else {
options.series[j].data.push(value); // push value to the series
}

Categories

Resources