Two line title in google chart api

二次信任 提交于 2020-01-23 16:47:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!