问题
I am using Google chart api to create a pie chart.
What I want here is to display the title in two lines.
One is the actual title and below that some info in small text.
How can I achieve this?
回答1:
So, just tried to get myself caught up on the API (guess they do this via javascript now and deprecated the image charts--good to know). Anyways...
There's a page on Pie Chart options, but nothing specific to per-line. You can split lines using \n
, but you're stuck with a uniform styling (via titleTextStyle
).
However, given the library outputs an SVG we have complete ability to manipulate the DOM after it's generated. Granted, I'm sure there's a fallback of some kind that google uses if SVG isn't supported, but if we can modify it, why not.
So, since the proof's in the pudding:
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var 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\nLast Night',
'titleTextStyle': {
'fontSize': '16'
},
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(chart_div);
chart.draw(data, options);
var heading = chart_div.getElementsByTagName('g')[0];
if (heading){
var title = heading.getElementsByTagName('text')[1];
if (title){
title.setAttribute('font-size', '10');
}
}
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
来源:https://stackoverflow.com/questions/30291037/two-line-title-in-google-chart-api