Update title dynamically on Apexcharts - javascript

I am using Updateseries to update x and y axis. How can i update title?
$.getJSON('chartData.php', {
devicename: feature.get('id')
}, (response) => {
chart.updateSeries([{
data: response
}])
let chart = new ApexCharts(document.getElementById("chart"), options)
chart.updateOptions({
title: 'Water Consumption per day on December 2019 for '
})
});

You should use the updateOptions method of ApexCharts to update any other configuration.
updateSeries only deals with data of the chart, while updateOptions allows changing the configuration of the chart dynamically
var chart = new ApexCharts(el, options);
chart.updateOptions({
title: {
text: 'new title'
}
})
Docs for updateOptions - https://apexcharts.com/docs/methods/#updateOptions

this code can update the title in the chart.
*ApexCharts.exec('id', "updateOptions", {*
title:{
text:title1
}
});

Related

How to create chart in google sheets with javascript?

I am using javascript to create Google-sheets-document with user data. The document is saved on the user's Drive.
I can't figure out how to make a graph from the data i have inserted. I am using vanilla javascript with the Google sheets API.
It would probably look something like this:
function createGraph() {
gapi.client.sheets.graph
.create({
properties: {
type(?): 'Pie'
spreadsheetid: //some id
range: 'A1:A10'
},
})
}
EDIT: To specify, i want to insert the graph to the sheets-document that i have created, not to the website.
If you want to add the chart to your spreadsheet, you can use Sheets API's AddChartRequest, as part of the spreadsheets.batchUpdate method.
Code snippet:
On broad terms, your request would look like this (check the reference below in order to build the request body in detail):
const payload = {
"requests": [
{
"addChart": {
"chart": {
"spec": { // Chart type, range source, etc.
"pieChart": { // Pie chart specification
// object (PieChartSpec)
}
// rest of ChartSpec properties
},
"position": { // Where the chart will be located
// object (EmbeddedObjectPosition)
}
}
}
}
]
}
const params = {
spreadsheetId = "YOUR-SPREADSHEET-ID",
body = payload
}
gapi.client.sheets.spreadsheets.batchUpdate(params);
Render chart in browsers and mobile devices:
In case you just wanted to render the chart in a browser, but not add it to your spreadsheet, you would use Google Charts (see Visualization: Pie Chart, for example).
Reference:
Sheets API > Charts
EmbeddedChart
ChartSpec
EmbeddedObjectPosition
PieChartSpec
Refer this example
<html>
<head>
<!--Load the AJAX API-->
<script
type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"
></script>
<script type="text/javascript">
var data;
var chart;
// Load the Visualization API and the piechart package.
google.charts.load("current", { packages: ["corechart"] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create our data table.
data = new google.visualization.DataTable();
data.addColumn("string", "Topping");
data.addColumn("number", "Slices");
data.addRows([
["Mushrooms", 3],
["Onions", 1],
["Olives", 1],
["Zucchini", 1],
["Pepperoni", 2]
]);
// Set chart options
var options = {
title: "How Much Pizza I Ate Last Night",
width: 400,
height: 300
};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(
document.getElementById("chart_div")
);
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width: 400; height: 300;"></div>
</body>
</html>
Referred from
https://developers.google.com/chart/interactive/docs/drawing_charts
I solved it. Thanks for the help! This worked for me.
function createGraphv2(spreadsheetIdGraph, endIndex) {
var params = {
// The spreadsheet to apply the updates to.
spreadsheetId: spreadsheetIdGraph, // TODO: Update placeholder value.
};
var batchUpdateSpreadsheetRequestBody = {
// A list of updates to apply to the spreadsheet.
// Requests will be applied in the order they are specified.
// If any request is not valid, no requests will be applied.
requests: [
{
addChart: {
chart: {
spec: {
title: 'Rapport',
basicChart: {
chartType: 'COLUMN',
legendPosition: 'BOTTOM_LEGEND',
axis: [
//X-AXIS
{
position: "BOTTOM_AXIS",
title: "FORBRUK"
},
//Y-AXIS
{
position: "LEFT_AXIS",
title: "TID"
}
],
series: [
{
series: {
sourceRange: {
sources: [
{
sheetId: 0,
startRowIndex: 0,
endRowIndex: endIndex,
startColumnIndex: 5,
endColumnIndex: 6,
},
],
},
},
targetAxis: "LEFT_AXIS"
}
]
}
},
position : {
newSheet : 'True'
}
},
}
}
],
// TODO: Add desired properties to the request body.
};
var request = gapi.client.sheets.spreadsheets.batchUpdate(
params,
batchUpdateSpreadsheetRequestBody
);
request.then(
function (response) {
// TODO: Change code below to process the `response` object:
console.log(response.result);
},
function (reason) {
console.error("error: " + reason.result.error.message);
}
);
}

Hightchart map pie : clic and hide specific pie

how can I hide a specific pie from a states when I'm clicking on this states ?
For example on this map :
https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/maps/demo/map-pies/
series: [{
mapData: Highcharts.maps['countries/us/us-all'],
data: data,
name: 'States',
....
events: {
click: function (e) {
e.point.zoomTo();
chart.update({
-- hide the state's pie
-- display data from serie on this specific state
})
}
}
I would like to hide California's Pie and zoom on this states to display an other serie of data instead (point for example)...
Thanks a lot for your help !
You need to find the right series and use setVisible metohd:
events: {
click: function(e) {
e.point.zoomTo();
Highcharts.find(chart.series, function(item) {
return item.name === e.point.id;
}).setVisible(false, false);
}
}
Live demo: https://jsfiddle.net/BlackLabel/czav0kL3/
API: https://api.highcharts.com/class-reference/Highcharts.Series#setVisible

how do i set json data set as labels for graph plot with c3.js

I have a line graph generated with c3.js with json data
the current chart is very simple
var chart = c3.generate({
bindto: '.balanceChart',
data: {
url: '/data',
mimeType:'json'
}
});
json data:
{
data1: [1000,1240,1270,1250,1280]
data2: [1000,240,30,-20,30]
}
chart looks good and is there
but it is currently plotting both sets of data
what i would like is for data2 to be the tooltip value of the plot
You can hide data2 from displaying like so
data: {
...
hide: ['data2']
}
From http://c3js.org/reference.html#data-hide
And use tooltip.format.value to change the tooltip display
tooltip: {
format: {
value: function (value, ratio, id, index) {
// return chart.data.values("data2")[index]; // if still wanting to use data2
// or get rid of data2 completely using this
var vals = chart.data.values(id); // id will be 'data1', vals will then be data1 array
return vals[index] - (index === 0 ? 0 : vals[index - 1]);
}
}
}
http://c3js.org/reference.html#tooltip-format-value
tooltip.format.title and tooltip.format.name will also be useful here to communicate to a user the value isn't actually that of data1 (maybe just changing the title to "Delta Data1")

Update HighCharts chart when AJAX Updates my data on my page

I have a Page where I have some Project Stats based on different Project Task Statuses. On this page I use AJAX to update my Stat values as they change.
I am now trying to integrate a Highcharts bar chart/graph and I need to update it;s chart when my data changes.
There is a JSFiddle here showing the chart I am experimenting with now http://jsfiddle.net/jasondavis/9dr345og/1/
$(function () {
$('#container').highcharts({
data: {
table: document.getElementById('datatable')
},
chart: {
type: 'column'
},
title: {
text: 'Project Stats'
},
yAxis: {
allowDecimals: false,
title: {
text: 'Total'
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.point.y + ' ' + this.point.name.toLowerCase();
}
},
subtitle: {
enabled: true,
text: 'Project Stats'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
credits: {
enabled: false
}
});
// Button Click to Simulate my Data updating. This increments the Completed Tasks bar by 1 on each click.
$(".update").click(function() {
var completedVal = $('#completed').text();
++completedVal
$('#completed').text(completedVal)
});
});
So this example is getting the data from a Table but I do not have to use this method, I could also set it with JavaScript if needed.
I just need to figure out how I can update all these values on the fly as my real live page updates my task stat values using AJAX so I would like this chart to update live as well.
Any help on how to make it update? When my AJAX code is ran, I could call some JavaScript at that point if there is a function that rebuilds the chart?
I would drop the use of the table, especially since it looks like you are building it just for highcharts to consume it. Instead return your data via AJAX as a Highcharts series object. and then use the Series.setData method to update your plot. This would be the right way to do it.
If you really want to use the table, you could query out the data and still use setData (this is what Highcharts is doing for you under the hood). Updated fiddle.
$(".update").click(function() {
var completedVal = $('#completed').text();
++completedVal;
$('#completed').text(completedVal);
// get y values
var yValues = $.map($('#datatable tr td'),function(i){return parseFloat($(i).text());});
// set data
Highcharts.charts[0].series[0].setData(yValues);
});

How do you make a bar a different color in KendoUI bar chart?

I'm am replacing my dot net charting with KendoUI. I'm showing a Score Distribution chart. I want all of the bars to be the same color except the bar with the median score and the Legend. How do I color a single bar a unique color? How would I color the Legend this new color?
Below is my old dotnet charting bar chart and below that is the new KendoUI chart I'm trying to replace it with. I just need to get that coloring right and we'll be in business. Any help is appreciated.
Update: I'm leaving the answer below this line intact in case there are those out there who are using an older version, but per a later comment, KendoUI now allows you to override styles for individual points in a series.
I don't believe you can, in the current version. That said, you can hack your way around the limitation.
You'll need to create two data series - one for your highlighted data, and one for everything else. Add both to you chart, and set them to stacked.
Here's a jsFiddle I put together to illustrate: http://jsfiddle.net/LyndsySimon/9VZdS/. It depends on KendoUI's CDN, so if it breaks in the future I apologize.
Here is the Javascript for reference:
$(function() {
var dataset = new Array(1,2,3,null,5,6);
var highlighted = new Array(null,null,null,4,null,null);
$('#chart').kendoChart({
theme: 'metro',
seriesDefaults: {
type: 'column',
stack: true
},
series: [
{
name: 'Not Highlighted',
data: dataset,
color: '#609'
},
{
name: 'Highlighted',
data: highlighted,
color: '#f03'
}
]
})
});​
Starting with the 2012 Q2 release, bar series support binding the point color to a data item field.
This is done through the colorField option. The Binding to local data online example demonstrates it.
Both the Kendo UI and the legacy wrappers for ASP.NET MVC expose it as an option:
.Series(series =>
{
series.Bar(model => model.Value, model => model.Color)
.Name("United States");
})
All series overloads can be seen here.
You could hack the SVG generated by the system. I have supplied the chart with a model which contains the colour for each bar. eg:
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Colour { get; set; }
public decimal Score { get; set; }
}
Which is used as a series on the chart. The view then looks like:
#(Html.Telerik().Chart(Model)
.Name("AverageScores")
.Theme("Simple")
.HtmlAttributes(new {style = "height: 500px"})
.Series(series => series.Column(s => s.Score).Name("Name").Color("Blue"))
.SeriesDefaults(sd => sd.Column().Labels(l =>
{
l.Visible(true);
l.Format("{0}%");
}))
.Title("Mean Percentage Scores")
.Legend(builder =>
{
builder.Position(ChartLegendPosition.Bottom);
builder.Visible(false);
})
.CategoryAxis(ca => ca.Categories(x => x.Code))
.Tooltip(builder =>
{
builder.Visible(true);
builder.Format("{0}%");
builder.Template("<#= dataItem.Name #><br/><#= value #>%");
})
.ValueAxis(va => va.Numeric().Labels(a => a.Format("{0}%")).Min(0).Max(100)
)
)
#section BelowTelerikScriptRegistrar
{
<script type="text/javascript">
function setAverageScoresColours() {
var data = $('#AverageScores').data("tChart").options.series[0].dataItems;
if (data != null) {
for (var i = 0; i < data.length; i++) {
var averageScore = data[i];
$($($('div#AverageScores svg g')[i]).children('path')[0]).attr('fill', '#' + averageScore.Colour);
$($($('div#AverageScores svg g')[i]).children('path')[0]).attr('stroke', '#' + averageScore.Colour);
}
}
}
$(document).ready(function () {
setAverageScoresColours();
})
</script>
}
The section BelowTelerikScriptRegistrar must happen after the Html.Telerik().ScriptRegistrar() is called.
This will work in Chrome, Firefox and IE10. I have noticed there is a problem with multiple chart and the timings around the generation of the SVG. Unfortunately you might have to wrap setAverageScoresColours() in a setTimeout function to ensure the SVG has been generated, but it seems to work with just one chart.
A bit hacky, but easier than managing lots of series.
And for KendoUI (which I have edited for...):
<div class="chart-wrapper">
<div id="chart"></div>
</div>
<script>
function createChart() {
$("#chart").kendoChart({
theme: $(document).data("kendoSkin") || "default",
title: {
text: "Internet Users"
},
legend: {
position: "bottom"
},
seriesDefaults: {
type: "column"
},
series: [{
name: "World",
data: [15.7, 16.7, 20, 23.5, 26.6]
}],
valueAxis: {
labels: {
format: "{0}%"
}
},
categoryAxis: {
categories: [2005, 2006, 2007, 2008, 2009]
},
tooltip: {
visible: true,
format: "{0}%"
}
});
}
$(document).ready(function () {
setTimeout(function () {
// Initialize the chart with a delay to make sure
// the initial animation is visible
createChart();
$($($('div#chart svg g')[0]).children('path')[0]).attr('fill', '#123');
$($($('div#chart svg g')[1]).children('path')[0]).attr('fill', '#321');
$($($('div#chart svg g')[2]).children('path')[0]).attr('fill', '#213');
$($($('div#chart svg g')[3]).children('path')[0]).attr('fill', '#312');
$($($('div#chart svg g')[4]).children('path')[0]).attr('fill', '#132');
}, 400);
});
</script>
Another way you can do it at runtime is using function which returns color.
API reference
Here is an example code:
<div id="chart"></div>
<script>
$("#chart").kendoChart({
series: [{
data: [1, 2],
color: function(point) {
if (point.value > 1) {
return "red";
}
// use the default series theme color
}
}]
});
</script>
This is not currently possible with current KendoUI version.
It's on their todo-list.
http://www.kendoui.com/forums/dataviz/chart/change-bar-column-color-for-each-point.aspx
There can be a kind of workaround, as said in the thread I've put here, it would be to describe a series for each color you need. It looks very inefficient to me, but it's currently the only way to do it. If you have only 1 chart, you could do it. Else, wait for a new version of KendoUI with this feature.
Telerik have recently released a Kendo UI Data Vis Theme Roller
http://demos.kendoui.com/themebuilder/dataviz.html

Categories