Resizing Google graphs to fit the full width and height of a div

Recently delving into Google charts and my goal is to generate a line graph that fits the available space. However, it appears that the charts are restricted by a particular aspect ratio since adjusting the height and width properties of both the chart and chart div element does not yield the desired dimensions.

Does anyone know if Google charts have a fixed aspect ratio or is there an option I overlooked for overriding it?

You can view an example here:

Thank you!

Answer №1

aside from specifying the width option,

make sure to set chartArea.width for optimal chart utilization of available space

moreover, it's crucial to redraw the chart when the window is resized

check out the functional code example below...

google.charts.load('current', {
  callback: function () {
    drawChart();
    $(window).resize(drawChart);
  },
  packages:['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y'],
    [0, 0],
    [1, 1],
    [2, 3],
    [3, 7],
    [4, 15],
    [5, 31]
  ]);

  var options = {
    chartArea: {
      // reserve space for y-axis labels
      width: '94%'
    },
    legend: {
      position: 'top'
    },
    width: '100%'
  };

  var container = document.getElementById('chart_div');
  var chart = new google.visualization.LineChart(container);
  chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


MODIFY

apart from others, chartArea also contains a property called left

instead of using chartArea.width: '94%', consider setting an absolute left value

refer to the operational snippet provided below...

google.charts.load('current', {
  callback: function () {
    drawChart();
    $(window).resize(drawChart);
  },
  packages:['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y'],
    [0, 0],
    [1, 1],
    [2, 3],
    [3, 7],
    [4, 15],
    [5, 31]
  ]);

  var options = {
    chartArea: {
      left: 40,
      width: '100%'
    },
    legend: {
      position: 'top'
    },
    width: '100%'
  };

  var container = document.getElementById('chart_div');
  var chart = new google.visualization.LineChart(container);
  chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Answer №2

Check out this demo that demonstrates how Google Charts can be made responsive. In this case, the charts are re-rendered upon the resize event:

$(window).resize(function(){
  renderGraph1();
  renderGraph2();
});

Answer №3

Following the recent Google Chart Updates in September 2021, one solution to ensure dynamic charts take up the full width of their container is to introduce a delay during loading.

setTimeout(function() {
  chart.draw(view, options);
  }, 2000
);

This issue arises when the page loads and the container's width is not yet defined due to its responsiveness, causing Google Chart to default to a width of 400 when it detects the parent container width returning 'NaN'.

However, the problem can be avoided by triggering the chart to load on click when all elements are properly rendered.

Even though the chart's width remains fixed upon loading and does not resize automatically, this aspect can be rectified using CSS.

Answer №4

Found myself facing a similar dilemma, where the space allocated for the graph within its container wasn't fully utilized.

For guidance, check out https://developers.google.com/chart/interactive/docs/gallery/linechart. Pay attention to the vAxis.viewWindowMode, vAxis.viewWindow.max, and vAxis.viewWindow.min properties, especially focusing on the "maximized" viewWindowMode:

Describes how to adjust the vertical axis in order to fit the values neatly within the chart area. The options include: [...]
"maximized" - Adjusts the vertical values so that the highest and lowest data points align with the top and bottom of the chart area. This overrides vaxis.viewWindow.min and vaxis.viewWindow.max.

If you're not utilizing the viewWindow, consider exploring the vAxis.ticks property as well, as it states, "The viewWindow will automatically expand to encompass the min and max ticks unless custom viewWindow.min or viewWindow.max are specified."

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a clickable element that triggers an action for a brief period of time before stopping automatically, using JavaScript, HTML, and CSS

Looking for a way to implement buttons or toggles that activate a feature for 3-5 seconds after the user selects them, without requiring further interaction. Any suggestions on how to achieve this using CSS, HTML, and JS? I currently have toggles in place ...

Custom CSS for the Google Maps Circle Object

Currently, I am utilizing the Google Maps Javascript API v3 Circle object to display circles on the map. I am interested in customizing the CSS of this circle by incorporating some CSS animations. Although I am aware that custom overlays can be used for t ...

Set the clock to the correct time by winding it up

I have created a vintage-inspired clock using javascript and css. function updateClock() { var now = moment(), second = now.seconds() * 6, minute = now.minutes() * 6, hour = now.hours() % 12 / 12 * 360 + 90 + minute / 12; ...

What is the best way to deactivate unclicked href links within a loop?

https://i.sstatic.net/sUufY.png Looking at the template image, my goal is to disable all links that were not clicked when one of the links from 'number1' to 'number3' is clicked. For example, if 'number2' is clicked, then &ap ...

Steps to Execute PHP Mail Form Script After Successful Form Submission

My HTML Form with PHP is causing an issue where the Mail() script runs automatically, sending me empty emails whenever someone visits the website. I need it to only run when the form is successfully submitted. Can you assist? <!--HTML FORM--><for ...

Can someone explain how the "class*=" selector functions in Django/Javascript/SQLite3? I'm curious about its purpose and how it operates

Embarking on a web development project in Django involving a database of ancient Greek and Latin texts previously worked on by others. Although I have some basic knowledge of Django and Javascript, there are still areas where I require clarification. Exam ...

Unlock maximum screen viewing on your custom video player with these steps to activate fullscreen

I'm having an issue with my basic video player - when toggling fullscreen, it doesn't fill the whole screen even though I tried using .fullscreen{width:100%} without success after searching for a solution. html <div class='player-contai ...

Is there a glitch in jQuery that causes other items in the UI to disappear when deleting a single item from local storage, even though they

After clicking delete on a record, it is successfully deleted from Localstorage. However, upon page reload, none of the "drop downs" show the other records in Localstorage even though they still exist. How can I address this issue? Seeking guidance on res ...

Items in Bootstrap row are not aligning in the center

Utilizing the Bootstrap 5 row property for responsiveness on my website, I encountered an issue where two divs placed next to each other did not align at the center of the webpage as expected. There was an unusual gap on the right that I couldn't elim ...

"What is the best way to access and extract data from a nested json file on an

I've been struggling with this issue for weeks, scouring the Internet for a solution without success. How can I extract and display the year name and course name from my .json file? Do I need to link career.id and year.id to display career year cours ...

Check if the list item contains any child elements and then add the

Is there a way to use jQuery to add a small down arrow icon next to each navigation item that has sub-items? Here is an example markup of the navigation: <div class="mainNav"> <ul> <li><a href="">Nav One</a> <ul> & ...

What is the best way to iterate through the child elements and access the "href" attribute for additional parsing?

My current project involves creating a parser for a local real estate website using python and selenium. I have successfully identified the necessary page and now I am looking to loop through each element in a parent directory to access additional pages fo ...

The issue of AJAX not being triggered a second time when a button is clicked using a jQuery click event

Whenever I click the button, an AJAX call is triggered to submit a form. The first click works fine and displays an error message if needed. But when I try clicking the button again, the AJAX call doesn't happen. However, if I replace the AJAX call wi ...

The picture won't stay within the confines of the container

As I work on my fitness site, I wanted to incorporate a sponsor section. While exploring some code that matched the style of my website, I discovered this snippet below. However, being new to CSS, I struggled with fixing it to ensure that the images fit ...

AdminLTE-3 Bootstrap-4 sidebar menu with dynamic AJAX functionality fails to toggle treeview open/hide after page is fully loaded

I am looking to update the sidebar menu dynamically in the adminlte 3 dashboard with bootstrap 4 using AJAX calls. However, I have run into an issue where the menu open/close functionality is not working when the data is loaded dynamically using AJAX. On t ...

What is the best way to handle the changing relative image URL in CSS minification?

The Issue Managing a large website with a deep CSS folder structure can present challenges when it comes to relative URLs for background images. Minifying CSS files before deployment can cause issues with these relative URLs due to the flattening of the f ...

Unattractive mobile modal

Hey there, This is how my .modal CSS code appears: .modal { position: fixed; top: 10%; left: 50%; z-index: 1050; width: 560px; margin-left: -280px; background-color: #fff; border: 1px solid #999; border: 1px solid rgba ...

Looping through radio buttons in jQuery to discover the container div with the most economical price

Is it possible to utilize Jquery to identify the lowest price, apply a class to the surrounding element, and update the 'checked="checked"' attribute to the correct option? <div><input type="radio" name="RateID" value="1" checked="check ...

Having trouble with the jquery fadetoggle function?

Greetings, I am currently working on a project with jQuery and facing an issue with the fadetoggle function. My setup includes JQuery 1.7.2 and the correct source connection to the file in the folder (I have successfully run other jQuery events). The cod ...

Sending arrays from HTML table rows to a JavaScript function

When developing a dynamic table using Javascript, I am able to add rows programmatically with the following function: function addrow(tableid) { var tablename = document.getElementById(tableid); var rows = tablename.rows.length; if (rows < ...