I am currently working with Google chart, Gauge chart. i want to add % along with the data value. How can I do that.
Screen shot is attached for reference.
I want to make 3.9% rather than only 3.9 at bottom
EDIT
this.data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Download%', {v:0,f:'0%'}]
]);
And in my update function
drawChart() {
this.data.setValue(0, 1, this.progress);
this.chart.draw(this.data, this.options);
}
Related
I am trying to build a watchOS app that has charting and I can't use Swifts built in charts because I need to support down to version 7 and swift charts are only available for watchOS 9+. So instead I am using a library I found here...
https://github.com/willdale/SwiftUICharts
It has some sample and examples, trying to follow them I was able to get the chart to show up and customize it some, but I can't get the bar chart items to change their color. It seems simple enough, but for whatever reason I can't get it to actually change the color.
I'll provide a simple sample that should help show what's going on.
struct ChartView: View {
var items: [TimeEntries] = [
TimeEntry(dateString: "01/23/2023", entry: 97, timestamp: Date().millisecondsSince1970)]
var body: some View {
let chartData = makeData(items)
BarChart(chartData: chartData)
.touchOverlay(chartData: chartData)
.padding()
}
private func makeData(_ items: [TimeEntries]) -> BarChartData {
var data: [BarChartDataPoint] = [BarChartDataPoint]()
for item in items {
let stat = BarChartDataPoint(
value: Double(item.entry),
xAxisLabel: "Wed",
date: Date(milliseconds: entry.timestamp),
colour: ColourStyle(colour: Color.purple)
)
data.append(stat)
}
let dataSet = BarDataSet(dataPoints: data)
return BarChartData(dataSets: dataSet)
}
}
That should give me an entry on my bar chart with purple filling, I simplified this for sake of ease of posting, my real data has 7 points in it.
However, what actually happens is I have a single red bar on my chart. I am not using red anywhere in the app at all, but it won't take the color that I specify in the colour property of the BarChartDataPoint.
I know it's based on a library, but hopefully someone here will have used this library and will know what I have done wrong. I'll attach a screenshot of the chart so you can see. Thank you.
I have multiple charts showing different data. however they are all the same object type e.ge [acc1, acc2, acc3]. Therefore I was wondering if it is possible to have one parent legend set on a page somewhere and clicking it will show/hide all the corresponding dataset from all the charts?
I think you can hide all the legends of the charts except for one and implement a custom onClick function to handle clicks on that legend and hide all the corresponding datasets for each chart.
The current onClick implementation looks like this:
onClick: function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var meta = ci.getDatasetMeta(index);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
ci.update();
}
This function needs to be defined in options.legend.onClick. To make this work you would need to rewrite the above function to implement a loop, selecting all the charts necessary and select the meta, hide it and update the chart.
I'm hoping to find a way, using Keen's visualization library, to integrate Google Chart's ChartRangeFilter (https://developers.google.com/chart/interactive/docs/gallery/controls#chartrangefilter). The section in Keen's docs (https://github.com/keen/keen-js/blob/master/docs/visualization.md#line-chart) related to line charts doesn't seem to afford any chart wrappers or controls.
In short, is there any way to render a line chart with a ChartRangeFilter using Keen out of the box? Or would I have to ask for the raw data and do the charting for myself?
Looking at the sample code and Google chart's instructions from https://developers.google.com/chart/interactive/docs/gallery/controls#using-controls--and-dashboards you'll need to combine code from Google into the charting portion after your result is computed from Keen.
You will first prepare your data (in your case, using the data result returned from Keen IO), then create a dashboard, and lastly draw/render the components (including the chartRangeFilter). Drawing the range filter for the chart is a modification to the existing visualization that can be graphed with Keen IO.
// Load the Google Visualization API and the controls package.
google.charts.load('current', {packages:['corechart', 'table', 'gauge', 'controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(init);
function init(){
client
//Run your Keen Query/Analysis Call
.query('count', {
event_collection: 'add_to_carts',
timeframe: {
start: '2016-09-01',
end: '2016-09-12'
},
interval: 'hourly',
timezone: 'US/Pacific'
//group_by: 'product_name'
})
.then(function(res){
var chart = new Dataviz()
.data(res)
drawDashboard(chart.data());
})
.catch(function(err){
console.log('err');
});
}
// Callback that creates and populates a data table,
// instantiates a dashboard, a range slider and a pie chart,
// passes in the data and draws it.
function drawDashboard(keenDataTable) {
// Create our data table.
var data = google.visualization.arrayToDataTable(keenDataTable);
// Create a dashboard.
var dashboardEl = document.getElementById('dashboard_div');
var dashboard = new google.visualization.Dashboard(dashboardEl);
// Create a range slider, passing some options
var chartRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control_div',
'options': {
'filterColumnIndex': 1,
'ui': {
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'height': '20%', 'width': '90%'},
'hAxis': {'baselineColor': 'none'}
}
}
}
});
// Create a pie chart, passing some options
var lineChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'chart_div',
'options': {
// Use the same chart area width as the control for axis alignment.
'chartArea': {'height': '80%', 'width': '90%'},
'hAxis': {'slantedText': false},
'vAxis': {'viewWindow': {'min': 0, 'max': 50}},
'legend': {'position': 'none'}
}
});
// Establish dependencies, declaring that 'filter' drives 'lineChart',
// so that the chart will only display entries that are let through
// given the chosen slider range.
dashboard.bind(chartRangeSlider, lineChart);
// Draw the dashboard.
dashboard.draw(data);
Here's a link to a JavaScript fiddle that runs this code and shows the Keen analysis result being rendered along with the Google range finder component:
http://jsfiddle.net/kuqod2ya/4/
This code sample uses the newest keen-analysis.js & keen-dataviz.js libraries. To access the Google Chart additional options include loader.js.
To track number of visitor comes through which website and do some analysis on the same. We are creating a column chart to show the analysis report in graphical form.
All the things are showing correctly on chart, but we are showing website name on haxis. As website name is too long like "www.google.com", www.facebook.com, this label are being cut off on haxis.
Code to draw chart is given below:
function createTodayChart(chartData){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sources');
data.addColumn('number', 'Total Sales');
for (var i in chartData){
//alert(chartData[i][0]+'=>'+ parseInt(chartData[i][1]));
data.addRow([chartData[i][0], parseInt(chartData[i][1])]);
}
var options = {
legend: {position:'top'},
hAxis: {title: 'Sources', titleTextStyle: {color: 'black'}, count: -1, viewWindowMode: 'pretty', slantedText: true},
vAxis: {title: 'Total Sales (in USD)', titleTextStyle: {color: 'black'}, count: -1, format: '$#'},
colors: ['#F1CA3A']
};
var chart = new google.visualization.ColumnChart(document.getElementById('my_div'));
chart.draw(data, options);
}
Data in chartData variable is in array form as:
var chartData = [];
cartData.push('www.w3school.com', 106);
cartData.push('www.google.com', 210);
Width and height of "my_div" are 350px and 300px respectively. We have also attached screen shot of this issue given below:
Can anyone help me that how can we prevent this cutting issue. Or, Is any method available in google chart API to prevent this?
Waiting for solution.
This is an always recurring issue in google visualization, in my opinion :( There are a few "tricks" one can experiment with : chartArea and hAxis.textPosition. Here is your code in a jsFiddle with the following chartData, reproducing the problem above :
var chartData = [
['www.facebook.com', 45],
['http://www.google.com', 67],
['www.stackoverflow.com', 11]
];
fiddle -> http://jsfiddle.net/a6WYw/
chartArea can be used to adjust the upper "padding" taking space from the legend / hAxis below along with the internal height of the bars (the chart itself without axis and legend). For example
chartArea: {
top: 55,
height: '40%'
}
Will shrink the chartArea, giving room for the legend on the hAxis.
fiddle -> http://jsfiddle.net/Swtv3/
My personal favourite is to place the hAxis legend inside the chart by
hAxis : { textPosition : 'in' }
This will honor both short and long descriptions, and does not make the chart looking too "weird" when there is a few very long strings.
fiddle -> http://jsfiddle.net/7HBmX/
As per comment - move the "in" labels outside the chart. There is to my knowledge no native way to do this, but we can always alter the <svg>. This can be a difficult task, but in this case we know that the only <text> elements who has the text-anchor="middle" attribute is the h-axis labels and the overall h-axis description. So
var y, labels = document.querySelectorAll('[text-anchor="middle"]');
for (var i=0;i<labels.length-2;i++) {
y = parseInt(labels[i].getAttribute('y'));
labels[i].setAttribute('y', y+30);
}
to move the labels outside the chart. demo -> http://jsfiddle.net/970opuu0/
Ok, so I'm really hoping someone can help me get started, I have been able to plot pies and timelines from my google analytics data via api with google visualization. I now want to extract the data from google analytics of visits and plot a geomap. This is the geomap sample code which works
google.load('visualization', '1', {packages: ['geochart']});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700],
['South Africa', 800]
]);
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, {width: 556, height: 347});
}
google.setOnLoadCallback(drawVisualization);
but of course I want to get the var 'data' from my google analytics api into such an array and plot say the top 10 popular countries based on pageviews from the last 30 days?
I believe the following query will give me what I want
dimensions=ga:country
metrics=ga:visits
sort=-ga:visits
How do I get this into the proper format for the data variable to plot this geomap? If you can help me rewrite the var data so that it works, I could be the happiest man alive.
Thanks in advance
This function should take the data returned by Google Analytics, input it into a DataTable, and draw a GeoChart of the top 10 countries by visit count:
function drawChart(results) {
var entries = results.feed.getEntries();
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Visits');
for (var i = 0; i < entries.length; i++) {
data.addRow([entries.getValueOf('ga:country'), parseInt(entries.getValueOf('ga:visits'))]);
}
// sort by visits, descending
var sortedRows = data.getSortedRows([{column: 1, desc: true}]);
// remove all elements after the 10th
while (sortedRows.length > 10) {
sortedRows.splice(10, 1);
}
var view = new google.visualization.DataView(data);
view.setRows(sortedRows);
var geochart = new google.visualization.GeoChart(document.getElementById('visualization'));
// draw the chart using the view
geochart.draw(view, {width: 556, height: 347});
}
You should look into using the new Google Analytics SuperProxy, it simplifies the process of getting api queries into the charts api, there are still a few bugs but very simple to setup, the youtibe video on the link below will take you through the full process. https://developers.google.com/analytics/solutions/google-analytics-super-proxy