When i put this below code i came with on visualization playground i get the Goal/Target line, but i want it to be dashed/dotted which requires certainty role as specified in the docs. Can anyone enlighten me how to do it with a array input to Google Datatable, or Datatable json string format
Code
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Red', 'Yellow', 'Green','Target'],
['2003', 20, 0, 0,80],
['2004', 0, 55, 0,80],
['2005', 0, 0, 80,80],
['2005', 0, 0, 85,80]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"},
legend:'none',
colors:['red','yellow','green'],
//isStacked: true,
series:{
3:{type:'steppedArea',areaOpacity:0}
}
//interpolateNulls: true
}
);
}
Update
I got it to this level below, with the code but how do i make the line stretch graph width
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month'); // Implicit domain label col.
data.addColumn('number', 'Sales'); // Implicit series 1 data col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'boolean',role:'certainty'}); // certainty col.
data.addRows([
['Red',20, 0,0, 80,true],
['Yellow', 0, 55, 0, 80,false],
['Green', 0, 0, 85, 80,false]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"},
legend:'none',
colors:['red','yellow','green'],
//isStacked: true,
series:{
3:{type:'line',areaOpacity:0}
}
//interpolateNulls: true
}
);
}
PlayGround:
https://code.google.com/apis/ajax/playground/?type=visualization#column_chart
Roles Docs:
https://developers.google.com/chart/interactive/docs/roles
So what is the right JSON format for dashed lines?
Is there any, i mean anyway i can display a arrow indicator at the right corner of the Target line to visually indicate the Goal?
You can achieve this by creating empty columns at the beginning and end of your chart, and then setting the view window to be within the range that you actually want. The code below achieves this:
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month'); // Implicit domain label col.
data.addColumn('number', 'Sales'); // Implicit series 1 data col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'boolean',role:'certainty'}); // certainty col.
data.addRows([
['', null, null, null, 80, false],
['Red',20, 0,0, 80,true],
['Yellow', 0, 55, 0, 80,false],
['Green', 0, 0, 85, 80,false],
['', null, null, null, 80, true]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"},
legend:'none',
colors:['red','yellow','green'],
//isStacked: true,
series:{
3:{type:'line',areaOpacity:0}
},
hAxis: {
viewWindow: {
min: 1,
max: 4
}
}
//interpolateNulls: true
}
);
}
Related
I have a column chart which I am trying to set the vertical axis scale to whole numbers i.e. 0, 1, 2... instead of 0, 0.5, 1...
Using vAxis : {format : '#'} merely rounds up the decimals, leaving duplicates i.e. 0, 1, 1, 2, 2...
Using vAxis : { gridlines : { count : 5 // for example } } does not seem to have an effect.
Ticks look like a solution but my question is what if my chart is to be dynamic? If I don't know what the max number of jobs would be, so as to set the ticks?
The last resort seems to be putting a height constraint on the chart, forcing the v-axis unit to be larger.
Thank you in advance!
to use ticks and still be dynamic,
you can use data table method getComumnRange(columnIndex)
to determine the min and max values of the y-axis values
then use those values to build the ticks array,
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['category', 'value'],
['a', 1],
['b', 10],
['c', 4],
['d', 3],
['e', 7]
]);
var yAxisRange = data.getColumnRange(1);
var ticks = [];
for (var i = 0; i <= yAxisRange.max; i++) {
ticks.push(i);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {
vAxis: {
format: '0',
ticks: ticks
}
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Just to preface, I'm very new to code! I'm working with Chart.js to show the number of recruitment candidates generated from a marketing campaign. I'm trying to display the data generated on a weekly basis. So I'll have a start date and the x-axis will show every next week. Right now, I can only get it to show every day. Again, I'm not well versed on the topic just yet so I apologize if I'm not explaining it properly. For this example the x-axis would sat 2020/11/20, 2020/12/07, 2020/12/14 and so on. Thanks!
What I have so far
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js'></script>
<canvas id="timeSeriesChart"></canvas>
<script>
Chart.defaults.global.defaultFontFamily = 'Poppins';
const ctx = document.getElementById('timeSeriesChart').getContext('2d');
const startDate = new Date(2020, 10, 30);
const labels = [];
for (let i = 0; i < 13; i++) {
const date = moment(startDate).add(i, 'days').format('YYYY/MM/DD');
labels.push(date.toString());
}
const chart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Recruitment Candidates',
data: [4, 5, 6, 90, 56, 32, 14, 6, 72, 99],
borderWidth: 1
}]
},
options: {}
});
</script>
Welcome to the world of coding. Never mind asking questions - it's professional, and we all started one day :-)
I hope I understood correctly your need and offer a solution right away with latest version:
Chart.js v3.xx (not compatible with v2.xx)
Time Series Axis (with moment.js + adapter):
Source: https://www.chartjs.org/docs/latest/axes/cartesian/timeseries.html
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
//gets you the latest version of chart, now v3.2.1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
//you need this adapter for timeseries to work with momentjs
<div>
<canvas id="timeSeriesChart"></canvas>
</div>
<script>
Chart.defaults.font.family = 'Poppins';
// watch out, it's not Chart.defaults.global.defaultFontFamily anymore as in v2.xx
const ctx = document.getElementById('timeSeriesChart').getContext('2d');
const startDate = new Date(2020, 10, 30);
const labels = [];
let i = 0;
//tip: declare variable `i` outside `for ()` loop - better performance
let date = new Date();
//also: declare variable `date` outside `for ()` loop
for (i; i < 13; i++) {
date = moment(startDate).add(i, 'weeks').format('YYYY/MM/DD');
//add `weeks` instead of `days` if you have weekly totals
//add `days` if you have daily totals
labels.push(date.toString());
}
const chart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Recruitment Candidates',
data: [4, 5, 6, 90, 56, 32, 14, 6, 72, 99],
borderWidth: 1,
tension: 0.3,
fill: true
}]
},
options: {
scales: { //watch out here - new syntax in v3.xx
x: {
type: 'timeseries',
time: {
unit: 'week', //this does the trick :-)
isoWeekday: true,
// declare Monday as the first day of the week
// because in some locale, sunday would be first day of week
}
}
}
}
});
</script>
You should get following result:
Hope this helps and happy coding ...
I'm noob at Phaser 3 and trying to add a group (2 sprites) in a follower. The code works when I use a sprite at 'add.follower'.
function create () {
var bola = this.add.group();
bola.create(0, 0, 'bola15');
bola.create(0, 0, 'bolasombra');
var line1 = new Phaser.Curves.Line([ 100, 100, 500, 100 ]);
var line2 = new Phaser.Curves.Line([ 500, 100, 500, 500 ]);
path1 = this.add.path();
path1.add(line1);
path1.add(line2);
var mover = this.add.follower(path1, 0, 0, bola);
mover.startFollow({
positionOnPath: true,
duration: 3000,
yoyo: false,
repeat: 0,
rotateToPath: false,
verticalAdjust: true
});
}
That's what I got:
Any solution for that, or other way to make something like that?
Edit:
Have tried with 'container' and got the same result:
bola = this.add.container(0,0);
bola1 = this.add.sprite(0,0,'bola15');
bola2 = this.add.sprite(0,0,'bolasombra');
bola.add(bola1);
bola.add(bola2);
At current state, PathFollower is set up to take in only a single GameObject. Unfortunately, this means you'll have to add your group items to a follower one by one. You can set up a loop to run through your group items and create the path followers like this:
for (var i = 0; i < bola.children.entries.length; i++) {
var mover = this.add.follower(path1, 0, 0, bola.children.entries[i].texture.key);
mover.startFollow({
positionOnPath: true,
duration: 3000,
yoyo: false,
repeat: 0,
rotateToPath: false,
verticalAdjust: true
});
}
Check this example from the Phaser 3 labs to see another example of how you can use multiple items with the same path if the group structure isn't important to your game.
I'm trying to colour the rows of paper-datatable
using the attribute customRowStyle
This Plunk of paper-datatable is working, rows are colored, but it's not enclosed as separate Polymer element.
I need to enclose paper-datatable in separate element.
Need some help to fix this:
how to make customRowStyle(item) to get called on table render and pass the item?
<paper-datatable data="{{data}}"
custom-row-style="{{generateRowCss}}"
on-row-tap="row_tap">
<paper-datatable-column header="title" property="title"></paper-datatable-column>
<paper-datatable-column header="Calories" property="calories"></paper-datatable-column>
<paper-datatable-column header="Fat (g)" property="fat" ></paper-datatable-column>
</paper-datatable>
...
generateRowCss: function (item) {
console.log('theming_2 generateRowCss:');
var levels = ['#FFFFFF', '#FFEBEE', '#FFCDD2', '#EF9A9A'];
var min = 150;
var max = 450;
var level = Math.floor((item.calories - min) / (max - min) * levels.length);
return 'background:' + levels[level] + ';';
},
EDIT:
Plunk with #a1626 solution.
As generateRowCssthat is passed to customRowStyle is a function rather than the return value of the function(which is what your code is passing) you'll have to do something like this. Instead of creating a function generateRowCss create a property with the same name, initialize it as Object and return its value as whole function
properties: {
data: {
type: Array,
notify: true,
value: [
{id: 0, title: 'Frozen yogurt', calories: 159, fat: 6},
{id: 1, title: 'Ice cream sandwich', calories: 237, fat: 9},
{id: 2, title: 'Eclair', calories: 262, fat: 16},
{id: 3, title: 'Cupcake', calories: 305, fat: 3.7},
],
},
generateRowCss:{
type:Object, //this is optional you can skip this also
value:function(){
return function(item){
console.log('app.generateRowCss');
console.log(item);
var levels = ['#FFFFFF', '#FFEBEE', '#FFCDD2', '#EF9A9A'];
var min = 150;
var max = 450;
var level = Math.floor((item.calories - min)/(max-min)*levels.length);
console.log(level);
console.log('background:'+levels[level]+';');
return 'background:'+levels[level]+';';
}
}
}
},
Pasted above are the properties of your custom element. Here is the working plunkr
I have a Google Visualization Column Chart from a query that works fine. I can set the a columns with a style role after the query by using the code snippet below. It adds a new column to the query data and sets the role as "Style". This colors each of the column chart bars accordingly. But I want to be able to use one of my query columns "C" for example as the color code and not have to add it afterward. I can't seem to get this to work. Any ideas? I posted more of my code below the snippet so you can see where I'm coming from. Thanks so much guys for any help you can give. Brandon
var data = response.getDataTable();
data.addColumn({type: "string", role: "style" });
data.setCell(0,2,'red');
data.setCell(1,2,'orange');
data.setCell(2,2,'green');
data.setCell(3,2,'yellow');
// More code above this, but I ommited it.
function drawDashboard() {
var query = new google.visualization.Query(
'URL');
query.setQuery('SELECT A, B, C');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
data.addColumn({type: "string", role: "style" });
data.setCell(0,2,'red');
data.setCell(1,2,'orange');
data.setCell(2,2,'green');
data.setCell(3,2,'yellow');
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
// Create a range slider, passing some options
var scoreSlider = new google.visualization.ControlWrapper({
controlType: 'NumberRangeFilter',
containerId: 'filter_div',
options: {
filterColumnLabel: 'Class AVG'
}
});
var ClassFilter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'Classfilter_div',
options: {
'filterColumnLabel': 'Teacher Name','ui': { 'labelStacking': 'veClasscal','allowTyping': true,'allowMultiple': true
}
}});
// Create a Column Bar chart, passing some options
var columnChart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Math Proficiency by Class',
height: 320,
width: 500,
chartArea:{left:"10%",top:"10%",width:"80%",height:"60%"},
hAxis: {textStyle: {fontSize:14}, title: 'Teacher Name', titleTextStyle: {fontSize:14}, textStyle: {fontSize:14}},
vAxis: {minValue: 0, maxValue: 100, title: 'Math Proficiency AVG', titleTextStyle: {fontSize:14}, textStyle: {fontSize:14}},
legend: {position: 'none'},
animation: {duration:1500, easing:'out'},
colors: ['#a4c2f4','#3c78d8']
},
view: {columns: [0, 1, 2]}
});
// Define a table
var table = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: data,
containerId: 'table_div',
options: {
width: '400px'
},
view: {columns: [0, 1,]}
});
// Establish dependencies, declaring that 'filter' drives 'ColumnChart',
// so that the column chart will only display entries that are let through
// given the chosen slider range.
dashboard.bind([scoreSlider], [table, columnChart]);
dashboard.bind([ClassFilter], [table, columnChart]);
// Draw the dashboard.
dashboard.draw(data);
}// More code below this, but I ommited it.
I'm not sure how you would add this to a column in the query but...
using a DataView with a calculated column should work...
Assumes the value you want to test is in the second column -- index 1
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: "string",
role: "style",
calc: function (dataTable, rowIndex) {
if (dataTable.getValue(rowIndex, 1) < 0.69) {
return 'color: red;';
} else if ((dataTable.getValue(rowIndex, 1) >= 0.69) && (dataTable.getValue(rowIndex, 1) <= 0.79)) {
return 'color: yellow;';
} else {
return 'color: green;';
}
}
}]);