Google Sheet API => Sheet creation OK but can't set specific defaultFormat - google-sheets-api

I succeeded to create a sheet, but horizontal and vertical alignments are set to defaults, not the ones I tried to set.
Here is the code
spreadsheet_body = {
'properties': {
'title': str("sme_"+jour_heure.read()),
'defaultFormat': {
'horizontalAlignment': 'LEFT',
'verticalAlignment': 'MIDDLE'
}
}
}
print(spreadsheet_body)
# Création du fichier Google Sheet
request = service_sheet.spreadsheets().create(body=spreadsheet_body)
response = request.execute()
print (response)
My sheet is correctly created by vertical and horizontal alignments are not set.
print (spreadsheet_body)
prints:
{'properties': {'title': 'sme_18_04_2020\n', 'defaultFormat': {'horizontalAlignment': 'LEFT', 'verticalAlignment': 'MIDDLE'}}}
but
print (response)
prints:
{'spreadsheetId': '1F2o5F8B-efoAOkg-d3z_2tGcPhvlp8gtcvGOGkGvAGI', 'properties': {'title': 'sme_18_04_2020\n', 'locale': 'en_US', 'autoRecalc': 'ON_CHANGE', 'timeZone': 'Etc/GMT', 'defaultFormat': {'backgroundColor': {'red': 1, 'green': 1, 'blue': 1}, 'padding': {'top': 2, 'right': 3, 'bottom': 2, 'left': 3}, 'verticalAlignment': 'BOTTOM', 'wrapStrategy': 'OVERFLOW_CELL', 'textFormat': {'foregroundColor': {}, 'fontFamily': 'arial,sans,sans-serif', 'fontSize': 10, 'bold': False, 'italic': False, 'strikethrough': Fal ./..
Title is OK but verticalAlignment is not ...
What did I do wrong ?

i believe you want to create new sheet with required alignment, with your code everything is a string like "horizontalAlignment": "LEFT" anything between "" is string and line ends with ; instead of ,
try this for creating new sheet and alignment
function alignment(){
//change sheet name as per your requirement
var ss = SpreadsheetApp.getActiveSpreadsheet().insertSheet("yousheet");
var range = ss.getRange("A1:Z");
range.setHorizontalAlignment('left').setVerticalAlignment('middle');
}

Related

how to set max legend width

I have right aligned legend and I need to give it max width 25% of whole chart container. I've tried set width to 25% but in case when my series name is short legend box still stays as 25% but should be equal to content width. So I am looking for maxWidth property if it exist. I am in styled mode. Here is the the code http://jsfiddle.net/sabira/xmcqjnvg/24/
Highcharts.chart('container', {
chart: {
styledMode: true,
},
legend: {
align: 'right',
layout: 'proximate',
},
series: [{
name: 'very long long long long long name',
data: [1, 4, 3, 5],
},
{
name: 'short',
data: [3, 5, 3, 1],
}]
});
The legend.maxWidth property doesn't exist. However, it can be achieved by checking legend width in the chart load event and update it when it is bigger than eg. '25%' of the chart width.
Code:
chart: {
styledMode: true,
events: {
load: function() {
var chart = this,
legend = chart.legend,
legendMaxWidth =
Highcharts.relativeLength(legend.options.maxWidth, 1) * chart.chartWidth;
if (legend.legendWidth > legendMaxWidth) {
legend.update({
width: legend.options.maxWidth
});
}
}
}
}
Demo:
https://jsfiddle.net/BlackLabel/fpwdtghk/
API reference:
https://api.highcharts.com/class-reference/Highcharts.Legend#update
For some one looking for an easier alternative to this just use itemWidth property of legend.
legend:{ itemWidth: 100 }
Updated Fiddle:
http://jsfiddle.net/3mvpbu1f/

Change Morris area chart

I would like to custom my area chart color, what should I do?
This is my code:
$.getJSON("http://10.30.6.69:1200/WebAPI.aspx/?api=RequestPostFiveMins", function (data4) {
new Morris.Area({
backgroundColor: '#ccc',
labelColor: '#060',
// ID of the element in which to draw the chart.
element: 'POSTFIVEMINS',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: data4,
// The name of the data record attribute that contains x-values.
xkey: 'Time',
// A list of names of data record attributes that contain y-values.
ykeys: ['Total', 'Success', 'Error'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Total', 'Success', 'Error'],
parseTime: false,
hideHover: 'auto',
}).progress(function () {
$(document.getElementById("POSTFIVEMINSID").style.display = "");
}).done(function () {
$(document.getElementById("POSTFIVEMINSID").style.display = "none");
});
Try adding the lineColors property which takes an Array containing colors for the series lines/points:
new Morris.Area({
// ...
lineColors: ['#0B62A4', '#F79263', '#A7B3BC'],
// ...
});

Google Chart getSelection doesn't have column property

When I use:
chart.getChart().getSelection()[0]
on a chart (from a chartwrapper, hence the getChart() first), the getSelection() function returns
only a row-property but no column property even though my 'chart' is a table and clicking anywhere within it should return both a row and column property.
Is this a known google charts bug? Does anyone know of a workaround?
Also I have found this topic on google groups:
https://groups.google.com/forum/#!topic/google-visualization-api/O_t7-s96A9w
here they say:
Currently the Table object only supports row selection and therefore the column property is always undefined. If this is important for you, you can catch these events by yourself by adding some special html code int he formatted value of each cell.
Anyone have an idea how to do this?
Even though google.visualization.table supports row selection only (it explains why column property returns null), you could consider the following approach to access column property:
google.load('visualization', '1', {
packages: ['table']
});
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time Employee');
data.addRows([
['Mike', {
v: 10000,
f: '$10,000'
},
true
],
['Jim', {
v: 8000,
f: '$8,000'
},
false
],
['Alice', {
v: 12500,
f: '$12,500'
},
true
],
['Bob', {
v: 7000,
f: '$7,000'
},
true
]
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
google.visualization.events.addListener(table, 'select', function(){
selectHandler(table);
});
table.draw(data, {
showRowNumber: false
});
}
function selectHandler(table) {
var selection = table.getSelection();
if(selection.length === 0)
return;
var e = event || window.event;
var cell = e.target; //get selected cell
document.getElementById('output').innerHTML = "Row: " + selection[0].row + " Column: " + cell.cellIndex;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="table_div"></div>
<div id="output"></div>
You can format your values with HTML, and pass 'allowHtml: true' in your draw options. Then your HTML can raise the event / execute the js that you want it to when a user clicks on the cell value.
For example, the items below will raise an alert when clicked on:
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time Employee');
data.addRows([
['Ted', {v: 10000, f: '<span onclick="alert(0)">$10,000</span>'}, true],
['Jim', {v:8000, f: '<span onclick="alert(1)">$8,000</span>'}, false],
['Alice', {v: 12500, f: '<span onclick="alert(2)">$12,500</span>'}, true],
['Bob', {v: 7000, f: '<span onclick="alert(3)">$7,000</span>'}, true]
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
google.visualization.events.addListener(table, 'select', function () {
var s = table.getSelection();
document.getElementById('row').innerHTML = s[0].row;
document.getElementById('col').innerHTML = s[0].column;
console.log(s);
});
table.draw(data, {showRowNumber: true, allowHtml: true});
}
google.load('visualization', '1', {packages:['table'], callback: drawTable});
See:
http://jsfiddle.net/fZzch/2/
A cleaner approach is to use a custom formatter:
How to write a custom formatter for Google DataTables (for use on visualisation api)

Dynamic Flot graph - show hide series by clicking on legend text or box on graph

I am working on dynamic flot graph with 3 series. My need is to hide/show series when clicked on legend. I have seen different examples that will work fine for static graphs but for dynamic graph, even it works first time but when graph is updated with new data values then everything is displaying with default options. once I hide the series, I want it to be hided until I click again to show it.
Here is my code. Basically, I am fetching data from JSON and updating the flot graph dynamically in 10 sec intervals. so new data will be shown every 10 sec and this is where the series is showing back again.
<div id="placeholder4" style="width:1000px;height:300px;background:#C89175"></div>
<script type="text/javascript">
$(function() {
somePlot = null;
togglePlot = function(seriesIdx)
{
var someData = somePlot.getData();
someData[seriesIdx].lines.show = !someData[seriesIdx].lines.show;
somePlot.setData(someData);
somePlot.draw();
}
// Initilizaiton of Series and Counter
var i = 0;
var data_Total = [[], [], []];
// data_Total[0] : Stip Data
// data_Total[1] : Decline Data
// data_Total[2] : Volume Data
//Setting Options for Graph Display
var options = {
points: { show: true },
//legend: {toggle: true },
series: {
lines: { show: true }
},
legend: {
labelFormatter: function(label, series){
return ''+label+'';
}
},
grid: {backgroundColor: "#FCFCFC", labelMargin:12,hoverable: true,tickColor:"#AD5C5C" },
xaxis: { mode: "categories", show:true,color:"white",axisLabel:'Time Series' },
yaxis:{show:true,color:"white",min:0,max:10000,axisLabel:'Total/ Stip/ Decline'}
}
//Function that will be called recursively with specified Time Interval
function fetchData() {
//Function that will push data in to Series1 thru an ajax call
function getDPSStipData(series) {
var stipItem = [series.data[i][0], series.data[i][1]];
data_Total[0].push(stipItem);
}
$.ajax({
url: "./JSon/stipdpssec.json",
method: 'GET',
dataType: 'json',
success: getDPSStipData
});
//Function that will push data in to Series2 thru an ajax call
function getDPSDeclineData(series) {
var declineItem = [series.data[i][0], series.data[i][1]];
data_Total[1].push(declineItem);
}
$.ajax({
url: "./JSon/declinedpssec.json",
method: 'GET',
dataType: 'json',
success: getDPSDeclineData
});
//Function that will push data in to Series3 thru an ajax call
function getDPSTotalVolumeData(series) {
var totalVolItem = [series.data[i][0], series.data[i][1]];
data_Total[2].push(totalVolItem);
}
$.ajax({
url: "./JSon/totaldpssec.json",
method: 'GET',
dataType: 'json',
success: getDPSTotalVolumeData
});
//Moving forward the ticks if size > 10
if (data_Total[0].length > 10)
{
data_Total[0] = data_Total[0].splice(1,10);
data_Total[1] = data_Total[1].splice(1,10);
data_Total[2] = data_Total[2].splice(1,10);
}
// Plotting of Graph
//$.plot($("#placeholder4"), [{ data: data_Total[2], label: "TotalVolume"},{ data: data_Total[0], label: "Stip",yaxis:2 }, { data: data_Total[1], label: "Decline",yaxis:2 }], options);
somePlot=$.plot($("#placeholder4"), [{ data: data_Total[2], label: "TotalVolume",idx:0},{ data: data_Total[0], label: "Stip",color: "green",idx:1 }, { data: data_Total[1], label: "Decline",color:"red",idx:2 }], options);
i++;
}
//fetchData
setInterval(fetchData, 10000);
});
</script>
Here's a quick example I put together for you.
somePlot = null;
togglePlot = function(seriesIdx)
{
var someData = somePlot.getData();
someData[seriesIdx].lines.show = !someData[seriesIdx].lines.show;
somePlot.setData(someData);
somePlot.draw();
}
var data = [
{
label: 'foo',
color: 'red',
data: [[1, 300], [2, 300], [3, 300], [4, 300], [5, 300]],
idx: 0},
{
label: 'bar',
color: 'blue',
data: [[1, 800], [2, 600], [3, 400], [4, 200], [5, 0]],
idx: 1},
{
label: 'baz',
color: 'yellow',
data: [[1, 100], [2, 200], [3, 300], [4, 400], [5, 500]],
idx: 2},
{
label: 'dart',
color: 'green',
data: [[1, 500], [2, 350], [3, 400], [4, 700], [5, 50]],
idx: 3}
];
somePlot = $.plot($("#placeholder"), data, {
series: {
lines: {
show: true
}
},
legend: {
labelFormatter: function(label, series){
return ''+label+'';
}
}
});
You can provide legend clicks in a way that survives rerendering the graph like so:
HTML:
<div id=graph></div>
JS:
$('#graph').on('click', 'div.legend tr', function() {
var tr = $(this);
var index = tr.parent().find('tr').index(tr);
// Do something with the fact they clicked item (index)
});
There's nothing stored in the legend marking what each row represents, so you'll need to bring that info in from someplace else - all the above code does is get you the index of the legend item clicked.
For usability you should tell the user this is clickable:
CSS:
#graph div.legend tr {
cursor: pointer;
}

JavaScript InfoVis Toolkit Error loading JSON from external file using AJAX

I have the code snippet shown below in my application . What I am trying to accomplish is this: anytime a checkbox is clicked, the bar chart should be updated.
In my error console I'm getting:
"Error: TypeError: values is undefined Source file:hit.js Line: 11017.
I tried assigning the JSON directly in the function (var json = ...) and it works as it should but I can't get it to work by loading the JSON from the file. What am I doing wrong?
$(':checkbox').click(function () {
init();
function init()
{
var request = new XMLHttpRequest( );
request.open("GET", "GetGenes.php", false);
request.send(null);
var json = request.response;
console.log(request.response);
var barChart = new $jit.BarChart({
//id of the visualization container
injectInto: 'infovis',
//whether to add animations
animate: true,
//horizontal or vertical barcharts
orientation: 'horizontal',
//bars separation
barsOffset: 0.5,
//visualization offset
Margin: {
top: 5,
left: 5,
right: 5,
bottom: 5
},
//labels offset position
labelOffset:5,
//bars style
type:'stacked',
//whether to show the aggregation of the values
showAggregates:true,
//whether to show the labels for the bars
showLabels:true,
//label styles
Label: {
type: 'HTML', //Native or HTML
size: 9,
family: 'Arial',
color: 'black'
},
//tooltip options
Tips: {
enable: true,
onShow: function(tip, elem) {
tip.innerHTML = "<b>" + elem.name + "</b>: " + elem.value;
}
}
});
barChart.loadJSON(json);
}
})
genes.php contains:
echo "{'label': ['label 1', 'label 2', 'label 3', 'label 4'],'values': [{'label': 'date A','values': [20, 40, 15, 5]}, {'label': 'date B','values': [30, 10, 45, 10]}, {'label': 'date E','values': [38, 20, 35, 17]}, {'label': 'date F','values': [58, 10, 35, 32]}, {'label''date D','values': [55, 60, 34, 38]}, {'label': 'date C','values': [26, 40, 25, 40]}]};";
There is an error in your returned JSON :
'label''date D'
There is a missing colon there. Don´t know if that solves anything.