How can I adjust the top margin of a legend that is placed at the bottom of a Doughnut chartjs graph?

I've been working on customizing doughnut graphs with ChartJS and I'm struggling to create space between the graph and the legend.

Here's my legend configuration:

plugins: {
  legend: {
    display: true,
    align: 'start',
    position: 'bottom',
  }
}

In an attempt to increase the height of the legend, I created this plugin:

const LegendMargin = {
  id: 'LegendMargin',
  beforeInit(chart, legend, options) {
    const fitValue = chart.legend.fit;

    chart.legend.fit = function fit() {
      fitValue.bind(chart.legend)();

      this.height += 40;
    }
  }
}

While this plugin successfully increased the height of the legend below the graph, the text within it remains aligned at the top of the box, which doesn't solve the issue.

Is there a way to align the text to the bottom of the box or add some margin/padding between the legend and the graph?

Thank you for any assistance!

Answer №1

To adjust the positioning of the legend at the top, you can utilize the legend.top property. However, keep in mind that this property is controlled by chart.js itself. Any changes made to it will be overwritten. One workaround is to use Object.defineProperty to intercept calls to legend.top, like so:

const LegendMarginPlugin = {
  id: 'LegendMarginPlugin',
  beforeInit(chart, legend, options) {
    const fitValue = chart.legend.fit;

    chart.legend.fit = function fit() {
      fitValue.bind(chart.legend)();

      let top;
      const marginTop = 30;

      Object.defineProperty(this, 'top', {
        get() {
          return top + marginTop;
        },
        set(v) {
          top = v;
        },
      });

      this.height += 40;
    };
  },
};

The values 30 and 40 provided here are just examples and may need to be adjusted based on your specific requirements.

Please note that since this approach relies on a non-public API, there is a possibility of it breaking in future releases. However, as of chart.js version 3.9.0, it is functioning properly for me.

An ideal solution would be for chart.js to introduce support for the full Padding object within the

options.plugins.legend.labels.padding
configuration option. This would allow for using padding.top directly. Currently, only a single numeric value is supported.

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

Querying two MongoDB collections simultaneously to locate a user based on their email address

I am working with two different collections, tutors and users, within my MongoDB database. Within the controller, I have a function called signin. In this function, I need to modify the condition so that it searches for a user in both the tutors and users ...

I struggle to grasp the significance of the scene's positioning

I've been experimenting with some sample code using three.js, where I've created a plane and I want it to rotate around. Here's a snippet of my code: This is the setup for my camera: var camera = new THREE.PerspectiveCamera(70, window.inner ...

Ensure that a child container automatically adjusts its width to fit within a parent container of varying width

There is a wrapping container that contains three floated containers inside. The width of the wrapping container is variable. The inner container on the left has a width of 100px, and the inner container on the right has a width of 500px. The center contai ...

Updating the parent page host within a cross-domain iframe: issues encountered in Firefox and Chrome browsers

I am encountering an issue with my iframe app where I am receiving an alert indicating "-error" in Chrome related to top.location.href. jQuery.ajax({ type : 'get', url : 'check_if_fb_data_set.php', success ...

Tips for retrieving the selected option from a dropdown list using ReactJS

Currently, I am attempting to extract the value of a dropdown menu structured like this: <ul className="tabs" data-component={true}> <li> <section className="sort-list" data-component={true}> <select value={0} class ...

Exploring the Power of NPM Modules in an Electron Renderer

Having trouble accessing lodash in an electron renderer. I'm a beginner with Electron and know that both the main process and renderer (local html file) have access to node. I can require something from node core like fs and it works fine, but when I ...

Troubulation with AngularJS: Why aren't my directives loading?

After working on my webpage Danieboy.github.io for some time, I took a 2-month break and returned to optimize it with the assistance of Dareboost. Making small changes like optimizing images and switching raw.github.com to rawgit.com, I thought everything ...

What methods exist for creating visual representations of data from a table without relying on plotting libraries?

Is there a way to plot graphs directly from a Data Table without the need for external graph libraries like plotly or highcharts? Ideally, I am looking for a solution similar to ag-grid where the functionality comes built-in without requiring manual code ...

Converting a JSON object with numerical keys back to its original form

Recently diving into JavaScript programming, I find myself struggling with reversing the keys of a single JSON object. Here is the specific object that I'm attempting to reverse: {70: "a", 276: "b ", 277: "c ", 688: "d", 841: "e", 842: "f", 843: ...

Unable to display image source in viewport

Currently, I am working on developing a basic ionic app that interacts with an API that I have created. I am encountering an issue where all data is being displayed correctly in the view except for the src attribute of an image. When I use console.log to c ...

Preserving quotation marks when utilizing JSON parsing

Whenever I try to search for an answer to this question, I am unable to find any relevant results. So please excuse me if this has been asked before in a different way. I want to preserve all quotation marks in my JSON when converting from a string. In m ...

Exploring the intricacies of debugging async/await in Node.js with the help of

Having trouble debugging an "await" instruction in my async function. Every time I try, a promise is returned instead of the expected value. I've noticed there's supposed to be an "Async" button where the red square is located in this picture but ...

JavaScript: Troubleshooting Array Formatting

Seeking assistance with formatting this JavaScript array accurately. It seems like I am overlooking something crucial: Javascript: <script type="text/javascript"> var dimensions = new Array("225","320","480", "--"); var walls = new Array() ...

Caution: Attempting to access a non-existent 'sequelize' property within a circular dependency in the module exports

Issue Nodemon server.js [nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Warning: connect.session() MemoryStore is not designe ...

What is the best way to utilize the node.js module passport-google?

I'm currently working on a node.js web application that prompts users to sign in using their Gmail account. While following instructions provided at this website, I modified the URL from www.example.com to localhost and launched the application. Howev ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

How to retrieve a value from ng-options using AngularJS?

I want to display a dropdown in which users can select a specific month. Currently, the dropdown is populated with all 12 months in an array. How can I make sure that only the selected month is fetched from the dropdown? Code Snippet: $scope.Month = [&ap ...

A different approach to calling JavaScript functions

I have a method that populates an array. I would like to utilize it in this manner: arrayname.fill("First Array"); And not like this: arrayname = fill("First Array"); What approach should I take? function fillArray(name) { let newArray = ...

Sending the id as a prop in react-router-dom

Is it possible to pass an ID in props to a React component using react-router-dom? Take a look at my app.js file below: <Switch location={this.props.location}> <Route exact path="/" component={Home} /> <Route path= ...

Issue with MVC Bundle not functioning properly in Release Configuration due to Debug being set to False, causing CSS and JS files to not

Whenever I deploy my MVC.Net application in release mode, the following configuration will be present in the web.config file: <compilation debug="false" targetFramework="4.5" /> After making the above changes, the site loads with CSS and JavaScript ...