Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview.

Despite exploring various solutions on both Stackoverflow and JSFiddle, none of them have proven effective in resolving this problem.

Below is a snippet of my code along with the resulting output:

Configuration Object for Chart :

    var options = {
        hAxis : {
            title : xAxis,
            textStyle:{
                color: 'black',
                fontSize : '8px'
            },
            slantedText : true,
            slantedTextAngle : 90,
            titleTextStyle : {
                fontSize : '15px',
                italic : false
            },
        },
        vAxis : {
            title : yAxis,
            format:format,
            textStyle:{
                color: 'black',
                fontSize : '8px'
            },
            titleTextStyle : {
                fontSize : '15px',
                italic : false
            },
            viewWindowMode : 'explicit',
            viewWindow : {
                min : 0,
                //max: 1200000
            }
        },
        backgroundColor : 'transparent',
        interpolateNulls: false,
        width : 350,
        height : 180,
        chartArea : {
            left : 40,
            width : '45%',
            height : '45%'
        },
     legend: {
          position: 'top',
            maxLines: 3,
        },
        series : {
            0 : {
                color : line1Color,
                visibleInLegend : true,
                pointShape: 'square',
                pointSize: 10,
            },
            1 : {
                color : line2Color,
                visibleInLegend : true,
                pointShape: 'diamond',
                pointSize: 10,
            }
        }
    };

Output:

Answer №1

Regrettably, there is no direct option to make the legend span multiple lines.

I struggled to stack the legends as shown in the screenshot; instead, they would get cut off with '...' at the end.

The only workaround I found was to increase the width significantly and also adjust the chartArea.width.

You could experiment with adjusting both width and chartArea.width until you achieve the desired layout.

Another important point, when using fontSize in the chart options, it should be a numerical value like 8, not a string like '8px'.

For reference, refer to the code snippet below...

google.charts.load('current', {
  callback: function () {
    var data = google.visualization.arrayToDataTable([
      ['Month', 'Tool - Long title could not read', 'Tool - Something to Prod Start'],
      [new Date('08/01/2015'), 0.2, 0.0],
      [new Date('09/01/2015'), 0.8, 0.0],
      [new Date('10/01/2015'), 1.0, 2.2],
      [new Date('11/01/2015'), 1.3, 1.2],
      [new Date('12/01/2015'), 1.8, 1.4],
      [new Date('01/01/2016'), 2.4, 1.5],
      [new Date('02/01/2016'), 2.5, 1.4],
      [new Date('03/01/2016'), 2.6, 1.5],
      [new Date('04/01/2016'), 2.5, 1.5],
      [new Date('05/01/2016'), 2.4, 1.6],
      [new Date('06/01/2016'), 2.3, 1.6],
      [new Date('07/01/2016'), 2.2, 1.5]
    ]);

    var options = {
        hAxis : {
            title : 'xAxis',
            format: 'MMM-yy',
            textStyle:{
                color: 'black',
                fontSize : 8
            },
            slantedText : true,
            slantedTextAngle : 90,
            titleTextStyle : {
                fontSize : 15,
                italic : false
            },
        },
        vAxis : {
            title : 'yAxis',
            format: '#,##0.0',
            textStyle:{
                color: 'black',
                fontSize : 8
            },
            titleTextStyle : {
                fontSize : 15,
                italic : false
            },
            viewWindowMode : 'explicit',
            viewWindow : {
                min : 0
            }
        },
        backgroundColor : 'transparent',
        interpolateNulls: false,
        width : 780,
        height : 180,
        chartArea : {
            left : 40,
            width : 310,
            height : '45%'
        },
        legend: {
            position: 'top',
            maxLines: 3
        },
        series : {
            0 : {
                color : '#154360',
                visibleInLegend : true,
                pointShape: 'square',
                pointSize: 10,
            },
            1 : {
                color : '#5499C7',
                visibleInLegend : true,
                pointShape: 'diamond',
                pointSize: 10,
            }
        }
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

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

Establish validation parameters for uploading multiple files

I need to implement client-side validation for my FileUpload control to ensure that users can only select up to 10 images. While I already have the server-side code in place, I now want to add client-side validation as well. Sample Code: <asp:FileUplo ...

Having trouble using angular.isString in conjunction with ng-repeat

Is there a way to use angular.isString for comparison within an ng-if in an ng-repeat loop? Currently, all items in the array are being returned. I attempted to simply display the result of angular.isString, but no output is generated. This is my desired ...

Is there a way to run only one instance of puppeteer.launch() and simply forward pages to it in Node.js?

I have a concern regarding the code snippet below. It appears to be launching the browser on every request, potentially causing server issues on Heroku. I would like to modify it so that puppeteer is launched as a Singleton instance, where it only needs ...

Creating a node.js function that can be used with OracleDB

I'm currently delving into learning nodeJS, but I'm facing a roadblock and can't seem to figure out what's causing the issue. Even the Debugger isn't providing much help. Any assistance or guidance would be greatly appreciated. The ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

Import objects into THREE.js using OBJLoader, convert to Geometry, apply transformations, and finally convert to BufferGeometry

Trying to figure out why the geometry loaded with OBJLoader cannot be smoothly shaded. var loader = new THREE.OBJLoader(manager); loader.load('/manmodel/js/man.obj', function (object, materials) { console.log(object); console.log(materia ...

Constructing a regular expression

I've been exploring JavaScript regular expressions and encountering some challenges while trying to build a larger one. Therefore, I have decided to seek help for the entire problem rather than just individual questions. What I am looking for is a re ...

JavaScript encountered an unexpected symbol, specifically the "=>" token

I encountered an issue while attempting to create a JavaScript function for deployment on Firebase: Error Message: Parsing error: Unexpected token => Here is the code snippet: exports.sendFriendRequest = functions.firestore.document("requests/{rUi ...

Unforeseen behavior in event binding causing knockout knockout

I implemented an event binding for the scroll event on a DIV. To add debounce functionality to the handler, I created a function on my model that generates the debounced handler. Then, in my view, I bind this factory function. I assumed that my factory fu ...

Flask causing AJAX Request to encounter a CORS Policy issue

Currently, I am utilizing Flask to construct a basic backoffice system. In an attempt to execute some requests on the client-side using AJAX, I keep encountering a persistent error: Access to XMLHttpRequest at '...' from origin 'http://lo ...

Using a custom font with Next.js and Tailwind: Font applied successfully but not displaying correctly

In my project with Next.js (9.4.4) and Tailwind.css (1.4.6), I am incorporating a custom font named SpaceGrotesk. To ensure its functionality, I stored the font files in public/fonts/spaceGrotesk, and then adjusted my configurations as below: // next.confi ...

Issue with React container not connecting properly

I am currently facing an issue with a search bar where the input value is not displaying properly. Even when I check the value in the console, it only shows one character at a time. https://i.stack.imgur.com/Qm0Lt.png My assumption is that there might be ...

Tips for preventing the need to open numerous chrome windows when running multiple URLs with Selenium WebDriverJS

Is there a way to prevent multiple instances of the browser from opening when attempting to parse multiple URLs? I would like to have just one browser open and running all the URLs within it. Any advice or suggestions would be greatly appreciated! I' ...

Ensuring payload integrity using microrouter: A step-by-step guide

I have utilized this code to develop a microservice const { json, send } = require('micro') const { router, post } = require('microrouter') const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) console.log(process.e ...

Ways to deselect checkboxes and eliminate validation requirements

Below is the HTML code snippet that I am working with: <div class="form-group"> <div class="input-group"> <label for="daterange-vacancy" class="input-group-addon">Van</label> ...

Issue with ngModel value not being accurately represented by checkbox state in Angular 2

My issue lies with a checkbox that does not reflect its ngModel value. To provide some context, I have a Service managing a list of products and a component responsible for displaying this list and allowing users to select or deselect products. If a user d ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

What is the method for sending an axios post request using the application/x-www-form-urlencoded content type?

How can I successfully send an axios post request using application/x-www-form-urlencoded? I am trying to include a refresh token in the request, but currently an empty object is being sent. However, I have verified that the token exists when checking "us ...

Switch out HTML dynamically using JavaScript/JQuery, embracing the principles of DRY coding

As a newcomer to front-end development, one issue I frequently encounter is avoiding repetition when dynamically generating HTML using JS/jQuery. Imagine you have a DOM object that has various states. Typically, all you need to do with JS is switch betwee ...