How can I center the title in a Line Chart from Google Charts API (Not Google Chart Images)
I don't see any options like titlePosition: 'center'
Thanks!
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['xValues', 'yValues'],
[0, 34.92],
[389, 39.44],
[488, 52.11],
[652, 55.4]
]);
var options = {
curveType: 'none', // 'function'
title: 'Title',
titleTextStyle: {
color: '333333',
fontName: 'Arial',
fontSize: 10
},
legend: 'none',
enableInteractivity: false
};
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
chart.draw(data, options);
}
This option is not provided by the API; you simply cannot do this.
I use:
titlePosition: 'none'
And insert a title with normal HTML
Another answer suggests something like the following:
$("text:contains(" + vencOptions.title + ")").attr({'x':'60', 'y':'20'})
Source: https://stackoverflow.com/a/16291236/364
$("text:contains(" + vencOptions.title + ")").attr({'x':'60', 'y':'20'})
//OR
$("#YOUR_GRAPH_WRAPPER svg text").first().attr("x", (($("#time-series-graph svg").width() - parseInt($("#YOUR_GRAPH_WRAPPER svg text").first().attr('x'),10)) / 2).toFixed(0));
After drawing the chart, call the event handler function:
google.visualization.events.addListener(chart, 'ready', Title_center);
And define the function as:
function Title_center(){
var title_chart=$("#payer_chart_div svg g").find('text').html();
$("#payer_chart_div svg").find('g:first').html('<text text-anchor="start" x="500" y="141" font-family="Arial" font-size="18" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">'+title_chart+'</text>');
}
Just insert the title of your chart and add the attributes X:500,y:141.
You can easily do this with the callback info from the chart after it has been drawn and a bit of math working on some text in a div.
Contain your chart in a position:relative div. Add a div under the chart and position both it and the chart absolute.
Then you can move the div's top & left positions with a little high-school math.
<https://jsfiddle.net/o6zmbLvk/2/>
$("#YOUR_GRAPH_WRAPPER svg text").first()
.attr("x", (($("#time-series-graph svg").width() - $("#YOUR_GRAPH_WRAPPER svg text").first().width()) / 2).toFixed(0));
See my explanation here
To show chart title in center of chart use below code snippet; it will dynamically set title in center of chart container.
Add ready event listener; google.visualization.events.addListener(myChart, 'ready', titleCenter); and add function titleCenter.
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawAxisTickColors);
var options = {
title: "Chart Title",
titleTextStyle: {
bold: true,
italic: true,
fontSize: 18,
},
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true,
};
function drawAxisTickColors() {
var data = google.visualization.arrayToDataTable([
['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General',
'Western', 'Literature', { role: 'annotation' } ],
['2010', 10, 24, 20, 32, 18, 5, ''],
['2020', 16, 22, 23, 30, 16, 9, ''],
['2030', 28, 19, 29, 30, 12, 13, '']
]);
var myChart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
google.visualization.events.addListener(myChart, 'ready', titleCenter);
myChart.draw(data, options);
}
function titleCenter() {
var $container = $('#chart_div');
var svgWidth = $container.find('svg').width();
var $titleElem = $container.find("text:contains(" + options.title + ")");
var titleWidth = $titleElem.html().length * ($titleElem.attr('font-size')/2);
var xAxisAlign = (svgWidth - titleWidth)/2;
$titleElem.attr('x', xAxisAlign);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
function Title_center(total) {
var title_chart = $("#chart svg g").find('text').html();
var x = $("#chart svg g").find('rect').attr('width');
var y = $("#chart svg g").find('rect').attr('y');
alert(x);
$("#chart svg").find('g:first')
.html('<text text-anchor="start" x="'+x/2+'" y="'+y+'" font-family="Arial" font-size="12" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">' + total + '</text>');
}
Create this fuction in script, and call after chart draw like:
google.visualization.events.addListener(chart, 'ready', Title_center("Test success"));
As previous answer said, you can´t config a centered title. Just don´t set any "title" config. By defult it will not be displayed.
Then you can set a title with HTML, some code:
<div>
<div style="text-align: center;">Some Centered Title</div>
<div id="chart_container">
<!-- THE CHART GOES HERE -->
</div>
</div>
Center chart tile
Dynamically adjust to title length
Overlaps with title from google.visualization.LineChart (not tested with other types of charts)
All this in 1 CSS class and 4 lines of JavaScript.
Answered here
document.getElementById('divid').getElementsByTagName('text')[0].setAttribute('x', '350')
svg > g:first-of-type > text {
transform: translateX(calc(50% - 150px));
}
Related
I would like to show label and percentage in Google pie chart. Is there any way to do it? In the docs, I found that it is possible to modify text with pieSliceText option. Possible values are:
label - show name of data (e. g. Apples)
value - show absolute value (e. g. 7)
percentage - show percentage value (e. g. 50%)
value-and-percentage - show both value and percentage (e. g. 7 (50%))
But is there something like label-and-percentage to show something like that Apples (50%)?
the only config option that will show both the label & percentage is for the legend...
legend: {
position: 'labeled'
},
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Tasks', 'Completed'],
['Morning', 28],
['Afternoon', 43],
['Evening', 80],
['Night', 161]
]);
var options = {
width: 900,
height: 400,
title: 'Tasks Completed',
pieHole: 0.5,
colors: ['#008000', '#ffbf00', '#FF0000','#4E6282'],
pieSliceText: 'value',
sliceVisibilityThreshold :0,
fontSize: 17,
legend: {
position: 'labeled'
},
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
You can show either label or percentage on pie charts. Look at the pieSliceText options here.
But if this is your requirement and you HAVE to show label and percentage both on pie chart that you can try this:
set, pieSliceText: 'value' in options.
And then pass formatted value in data of chart by calculating the percentage of every slice data and passing the label + percentage as formatted value:
data.addRows([
['Label', {v:value, f:'formatted value'}],
]);
here v: is the value of chart
and f: is formatted value of chart which in your case will be label +
percentage.
Eg:
[chartlabels, {v: chartvalue, f: chartlabels+" "+((100 * chartvalue) / totalofvalues).toFixed(2)+"%"}]
I'm using Google Charts to display pie charts. In my options variable, I have the legend set this: legend: {position: 'labeled', textStyle: {color: 'white', fontSize: 24}}
Now if you look at the image below, the font color only applies to the label name, but not the percentage text or the label line. Is there anything I can do to change the color for the percentage text and the label line to white?
change the css:
g g g text
{
fill: black;
}
didn't see an option that will change the text style for the charts elements mentioned
but the chart's svg can be modified manually
however, the chart will revert back to the default style,
whenever there is activity, such as hovering a slice
as such, a MutationObserver can be used to override the styles
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'y');
data.addRows([
['Moving to a new city', 25],
['Meeting new people', 12.5],
['Gaining independence', 62.5]
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(container);
var observer = new MutationObserver(function () {
$.each($('#chart_div path[stroke="#636363"]'), function (index, path) {
$(path).attr('stroke', '#ffffff');
});
$.each($('#chart_div text[fill="#9e9e9e"]'), function (index, label) {
$(label).attr('fill', '#ffffff');
});
});
observer.observe(container, {
childList: true,
subtree: true
});
chart.draw(data, {
backgroundColor: '#1f618d',
legend: {position: 'labeled', textStyle: {color: 'white', fontSize: 24}}
});
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
How can I create multiple x Axis labels using the google charts API?
Im trying to create a bar graph right now with the main x axis labels as "products" and the individual bars relating to the products in question. However, I would like to segregate a set of 'n' products (data coming in from a database) by months.
Essentially I want a main X Axis label "product" and a dividing line between each set of products and a label underneath this set of bar graphs pertaining to the products grouping together each 'product set' by month
Thanks in advance to anyone who can help me with this!!
Sample double x-axis bar chart with google charts. Taken from their api documentation which can be found here:
Double x-axis bar chart
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Galaxy', 'Distance', 'Brightness'],
['Canis Major Dwarf', 8000, 23.3],
['Sagittarius Dwarf', 24000, 4.5],
['Ursa Major II Dwarf', 30000, 14.3],
['Lg. Magellanic Cloud', 50000, 0.9],
['Bootes I', 60000, 13.1]
]);
var options = {
width: 800,
chart: {
title: 'Nearby galaxies',
subtitle: 'distance on the left, brightness on the right'
},
bars: 'horizontal', // Required for Material Bar Charts.
series: {
0: { axis: 'distance' }, // Bind series 0 to an axis named 'distance'.
1: { axis: 'brightness' } // Bind series 1 to an axis named 'brightness'.
},
axes: {
x: {
distance: {label: 'parsecs'}, // Bottom x-axis.
brightness: {side: 'top', label: 'apparent magnitude'} // Top x-axis.
}
}
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
<div id="dual_x_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Not sure if that is exactly what you want to do, but if not let us know and we can modify this slightly.
Here is my code:
var chart = [[''],['']];
chart[0][1]='Spearmint';
chart[1][1]='3.95';
var data = google.visualization.arrayToDataTable(chartArr);
var options = {
title: questions[i].getAttribute("desc"),
is3D: true,
width:600 //with or without this parameter
};
chart = new google.visualization.ColumnChart(document.getElementById('questionchart_' + questions[i].getAttribute("num")));
chart.draw(data, options);
It seems to be cutting off the legend text. You only need to reference the first graph
Here is an image:
Graph Image
If you look closely, you'll see the legends display Sp..... This is inaccurate as it should display the full name of the location (Spearmint).
Here is my DOM Element its using:
<div id="questionchart_1" style="width:750px"></div>
I have no idea how to resolve this issue.
The size of the chartArea needs to be adjusted according to the placement of the legend and the size of the labels that need to be displayed.
Also need to consider the size of the title, axis labels, etc...
Here, I've added a background color to help demonstrate...
google.charts.load('current', {
packages: ['corechart'],
callback: drawChart
});
function drawChart() {
var chartArr = [[''],['']];
chartArr[0][1] = 'Spearmint';
chartArr[1][1] = 3.95;
var data = google.visualization.arrayToDataTable(chartArr);
var options = {
chartArea: {
backgroundColor: 'cyan',
height: 320,
left: 32,
top: 40,
width: 434
},
height: 400,
legend: {
position: 'right'
},
title: 'Flavors',
width: 600
};
var chart = new google.visualization.ColumnChart(document.getElementById('questionchart_0'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="questionchart_0"></div>
I'm trying to display multiple google pie charts on the same page.
I get an Uncaught Error: Container is not defined error when doing so. How can I resolve this ?
My code :
function drawChart()
{
var completeness = $(this).attr('data-completeness');
var data = google.visualization.arrayToDataTable([
['Nom', 'Valeur'],
["Profil rempli à ", completeness],
['Manque', 100 - completeness]
]);
var options = {
...
};
var chart = new google.visualization.PieChart(this);
chart.draw(data, options);
}
$(function(){
$('.piechart').each(function(){
google.load('visualization', '1', {callback : drawChart, 'packages':['corechart']})
});
});
Alternatively, if I iterate in the drawchart function, the output of the piechart gets really weird, it's not an arc anymore but about 5% of an arc (which does not happen if I do not set the completeness dynamically) :
function drawChart(elem)
{
$(elem).each(function(){
{#var completeness = {{ completeness }};#}
var completeness = $(this).attr('data-completeness');
console.log(completeness);
var data = google.visualization.arrayToDataTable([
['Nom', 'Valeur'],
["Profil rempli à ", completeness],
['Manque', 100 - completeness]
]);
var options = {
backgroundColor: { fill:'transparent'},
pieSliceBorderColor : 'transparent',
pieHole: 0.8,
legend: {position: 'top'},
width: 220,
height: 220,
tooltip: {trigger: 'none'},
pieStartAngle: -90,
pieSliceTextStyle :{fontsize : 16, color: 'transparent'},
slices: {
0: { color: '#09b4ff'},
1: { color: '#444'}
},
chartArea : {width: '90%', height: '90%'}
};
var chart = new google.visualization.PieChart(this);
chart.draw(data, options);
});
}
$(function(){
google.load('visualization', '1', {callback : function(){drawChart('.piechart');}, 'packages':['corechart']})
});
You have to use the document get element id and post like below
var chart = new google.visualization.PieChart(document.getElementById('container'))
Make sure you have the same id (container) html div tag, otherwise this will lead error
The problem is the way you are calling var chart = new google.visualization.PieChart(this);
The issue is that you should be passing in an element on the page, but instead you are passing this which is likely simply window. If you have an element with an id of "container" that you wish to use, you can do this instead:
var chart = new google.visualization.PieChart(document.getElementById('container'));
You can check out an example here