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

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

The inefficiency of invoking Jquery on elements that do not exist for the purpose of caching

What is the impact if JQuery attempts to access elements that do not exist? Will there be any significant CPU overhead other than script loading? Does it matter if this is done for a class or an id? For optimization purposes and to minimize simultaneous c ...

What is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

Syntax error occurs while attempting to render the return statement in a React Component

Just starting out with React and encountering a syntax issue that has me stumped. I'm working on a React Component and I thought I had the opening/closing { & }'s correct, but clearly there's something missing based on the error message it&a ...

Normalization of Firebase Database

Recently, I developed a Tricycle Patrol app designed to address the prevalent issue of reckless tricycle drivers in our city. Users can log in and submit reports through a form that includes fields such as: - created_at - description - lat - lng - plateNu ...

Angular Boilerplate is experiencing difficulties in properly reading ABP

Working on my boilerplate project, I am now diving into consuming backend services (using asp .net) in Angular through http requests. However, I encountered an issue when trying to implement the delete method in mycomponent.ts, as TypeScript was not recogn ...

How can JavaScript be used to make an AJAX request to a server-side function?

I am diving into the world of AJAX and feeling a bit uncertain about how to structure my AJAX call. $.ajax({ type: "POST", url: "Default.aspx/function", data: '{ searchBy: id }', contentType: "application/json; charset=utf-8" }). ...

Tips on converting deeply nested JSON into an excel file using Node.js

I am attempting to convert the JSON data below into an Excel file using XLSX. Although it successfully converts my JSON to Excel, I encountered an issue where the nested array of dailyPointsArray appears blank after conversion. Code Attempted const XLSX ...

Navigating the scope set by a specific string

Is there a more efficient method than iterating through child objects to access the value at a specific location in the $scope, identified by the attribute "Calendar.Scheduling.field.Appointment.ApptDateTime_Date"? I was hoping for a solution similar to an ...

Nextjs optimizing page caching to reduce unnecessary rendering

Within my Next.js application, I have implemented two unique pages. Each page is designed to display a randomly selected person's name when the component is initially loaded. simpsons.tsx export default function Simpsons() { const [person, setPerso ...

Having trouble exporting a variable from one Node.js file to another and finding that the value remains unchanged?

Hey there, I've been working on exporting a variable to another file within my nodejs application. I have successfully exported the variable, however, I need it to update whenever a user logs in. Will the export automatically pick up on this change an ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

Is there a way to include a different component without it automatically displaying within a div element?

Is there a way to make the Torrent component render without directly binding it to a DOM element? I am facing an issue with my Torrent Table Component as I want it to be populated with Torrent Components based on API data, but it's not rendering beca ...

Ways to utilize a string as an object?

Hey there! I'm just getting started with software development and currently working on an application using React Native. The backend is sending me a large data set, but here's a snippet of it. My challenge is that I want to access the first ele ...

Checking if a string is present in an array object with Angular.js using a filter function

In my Angular and Firebase app, users can create new discussion topics and vote on existing ones. When a user is logged in, their username is stored in currentUser.username. If they've upvoted a topic, their username will also be added to the array of ...

Is there a way to retrieve a large number of users through an API using async await?

I am trying to retrieve all users from an API and I want to identify which user receives the highest payment. For instance let users=['tom','jenny','smith','Joe'] async function getUsers() { let response = awa ...

Is anyone else experiencing issues with the jQuery slide-in not working on a particular website? How can I determine which version of jQuery is compatible with this site?

Essentially, I am looking to have a div box slide in on the page as it loads. This method has worked successfully on other websites and HTML previews that I have tested it on so far. However, for some reason, it does not seem to work on this specific websi ...

Issue reported: "Usage of variable 'someVar' before assignment" ; however, it is being properly assigned before usage

This piece of code showcases the issue: let someVar: number; const someFunc = async () => { someVar = 1; } await someFunc(); if (someVar == 1) { console.log('It is 1'); } As a result, you will encounter ...

What is the process for retrieving a value from a Django view?

Would it be feasible to call a view from a JavaScript file using Ajax and have the view only return a specific value known as "this"? However, despite attempting this, an error occurs stating that the view did not provide an HttpResponse object, but instea ...

Is it possible to use multiple AJAX requests to automatically fill out form fields?

In my Backbone.js web application, there is a form with multiple dropdowns that need to be populated with data fetched from an API. Since all the application logic resides on the client side due to using Backbone.js, I want to avoid populating these dropd ...