google-visualization

How to put main title of google column chart in the center?


Here's my basic code to draw column chart using Google Charts API:

<meta charset="UTF-8">
<title>Google Charts</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);

function drawChart()
{
    var my_chart = document.getElementById("my_chart");

    var data = google.visualization.arrayToDataTable([
        ['Name', 'Marks'],
        ['Sachin', 85],
        ['Amit', 60],
        ['Rohit', 75],
        ['Deepak', 50],
        ['Rahul', 55]
    ]);

    var options = {
        title: "Students Marks",
        titleTextStyle: {
            color: "red",
            fontSize: 18,
            bold: false,
        }
    };

    var chart = new google.visualization.ColumnChart(my_chart);
    chart.draw(data, options);
}
</script>

<style type="text/css">
#my_chart {
    max-width: 900px;
    height: 500px;
    border: 1px solid #ccc;     
}
</style>
<div id="my_chart"></div>

I need to place main title of chart (Students Marks) in the center of chart. I can't see any option in official docs.

I tried a couple of options like titleTextPosition and titlePosition myself to test whether they work or not but they don't.

Does anybody know how to do that?


Solution

  • Here is your working code, instead of using titleTextStyle, put your css rules in the .googleChartTitle

    google.charts.load("current", {packages: ["corechart"]});
    google.charts.setOnLoadCallback(drawChart);
    
    function drawChart()
    {
        var my_chart = document.getElementById("my_chart");
    
        var data = google.visualization.arrayToDataTable([
            ['Name', 'Marks'],
            ['Sachin', 85],
            ['Amit', 60],
            ['Rohit', 75],
            ['Deepak', 50],
            ['Rahul', 55]
        ]);
    
        var options = {};
    
        var chart = new google.visualization.ColumnChart(my_chart);
        chart.draw(data, options);
      
       const node = document.createElement('div');
        node.className = 'googleChartTitle';
        node.innerHTML = 'Students Marks';
    
        // Insert the node inside the chart divs
        my_chart.childNodes[0].childNodes[0].append(node);
    }
    #my_chart {
        max-width: 900px;
        height: 500px;
        border: 1px solid #ccc;     
    }
    
    .googleChartTitle {
        text-align: center;
        position: absolute;
        width: 100%;
        padding-top: 8px;
        color: red;
        font-size: 18px
    }
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    
    <div id="my_chart"></div>