Adjust the size and color of text in Chart.js using Angular 5

Why does the font color in chartjs appear as light gray and not print when you want to do so from the page?

I tried changing the font color of chartjs in the options attribute, but it didn't work. How can I change the font color in chartjs angular?

public options:any = {

    legend: {
            labels: {
                // This specific font property overrides the global property
                fontColor: 'red',
                fontSize: '30'
            }
        }
  };

In the template:

<canvas baseChart
                height=100                
                [datasets]="barChartData"
                [labels]="barChartLabels"
                [options]="barChartOptions"
                [legend]="barChartLegend"
                [colors]="chartColors"
                [chartType]="barChartType"
                [options]="options"
                >
        </canvas>

This is how I use chartjs in my ts file:

Here is my complete ts file:

import { Component, Input, OnInit } from '@angular/core';

import { Test } from './models/test.model';

@Component({
  selector: 'app-customer-report-test',
  templateUrl: './customer-report-test.component.html',
  styleUrls: ['./customer-report-test.component.css']
})
export class CustomerReportTestComponent implements OnInit {

  @Input('test') test: Test = new Test();

  public barChartOptions:any = {
    scaleShowVerticalLines: false,
    responsive: true
  };
  public barChartLabels:string[];
  public barChartType:string = 'bar';
  public barChartLegend:boolean = true;

  public barChartData:any[];
  backgroundColorList: string[];
  public chartColors: any[] = [
      {
        backgroundColor: this.backgroundColorList
      }];


  public options:any;

  constructor() { }
  //----------------------------------------------------------------------------
  ngOnInit() {

    //set Label
    this.barChartLabels = [];
    for(let i=1; i<= this.test.data_array.length; i++){
      this.barChartLabels.push('' + i);
    }
    //set data chart
    this.barChartData = [{data: this.test.data_array, label: this.test.test_type[1]}]
    this.test.test_type[1]}, {data: [20,20, 20, 20],type: "line",label: ['0', '1', '2', '3'] ,fill:'none'}]

    // set color to line according to state_array
    this.backgroundColorList = [];
    if(this.test.state_array.length != 0){

      for(let i=0; i<this.test.data_array.length; i++){
        if(this.test.state_array[i] == 0){
          this.backgroundColorList.push('#069ed6');
        }else if(this.test.state_array[i] == 1){
          this.backgroundColorList.push('#F5482D');
        }else if(this.test.state_array[i] == 2){
          this.backgroundColorList.push('#CAC409');
        }
      }
   }
    else{
      for(let d of this.test.data_array){
        this.backgroundColorList.push('#069ed6');
      }
    }

    this.chartColors = [
        {
          backgroundColor: this.backgroundColorList
        }];

    this.options = {
      responsive: true,
      title: {
              display: true,
              text: 'Custom Chart Title'
          },

          legend: {
                  display: true,
                  labels: {
                      fontColor: 'red'
                  }
              }

    };
  }
}

Answer №1

To customize the appearance of numbers and lines in a coordinate plane, you can make the following adjustments. For instance, in the xAxes section:

xAxes: [{
    gridLines: {
        display: true,
        color: "blue" // modify this line     
    },
    ticks: {
        fontColor: "blue", // adjust this line     
    }
}],

You can also change the font style and color of labels using the following code snippet:

legend: {
    display: true,
    labels:{
        fontSize: 12,
        fontColor: 'blue',
    }
},

Check out the DEMO for a live example.

Answer №2

Need to customize your chart appearance? Here's a quick tip: 1. Navigate to /node_modules/chart.js/src/core/core.js in your node modules directory. 2. Locate the code snippet below in the core.js file and make changes as desired:

defaultFontColor: '#0000ff'

You can replace the color value with your preferred choice. I personally used this method for my pie chart customization, and it worked perfectly.

`

defaults._set('global', {

responsive: true,
responsiveAnimationDuration: 0,
maintainAspectRatio: true,
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
hover: {
    onHover: null,
    mode: 'nearest',
    intersect: true,
    animationDuration: 400
},
onClick: null,
defaultColor: 'rgba(0,0,0,0.1)',
defaultFontColor: '#0000ff',
defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
defaultFontSize: 12,
defaultFontStyle: 'normal',
showLines: true,

// Element defaults defined in element extensions
elements: {},

// Layout options such as padding
layout: {
    padding: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
    }
}
});

module.exports = function() {

// Use the Chart global variable and create a basic base class
var Chart = function(item, config) {
    this.construct(item, config);
    return this;
};

Chart.Chart = Chart;

return Chart;
};`

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

What is the best way to adjust and filter an array based on a single value?

Here is an array that needs to be modified: [ {name: "test", value: "test", group: 0}, {name: "test1", value: "test2", group: 0}, {name: "test3", value: "test3", group: 1}, {name: "te ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

transitioning from angular cli version 1.7 to version 12

Looking for a detailed guide on upgrading from version 1.7 to the latest Angular version (12/11)? I currently have an app running on version 1.7 and couldn't find a step-by-step process here: upgrading angular Would it be safe to assume that the upgr ...

Leveraging @Input in Angular 2 to transmit information to ng2-typewriter

Currently, I have integrated ng2-typewriter into my project and I would like it to function as a singleton for reusability. While most aspects are working smoothly, I am facing challenges with the plugin's predefined methods as I try to incorporate m ...

Change the background color of all cells in a Bootstrap table by hovering over a single cell

Here is the code for a bootstrap table: <body leftmargin="0" topmargin="0" bgcolor="#ffffff" marginheight="0" marginwidth="0"> <div class="container-fluid h-100"> <div class="row float-right align-items-center" style="height: 5%;"> ...

Creating a dynamic button with Angular that appears when focused

I want to have a button appear when the user focuses on an input with the ng-model=query. I know there is an ng-focus directive, but how can I implement it? <input type="search" ng-model="query"> <!--this is the button I need to show once th ...

Choosing the Active Browser Tab while Modal is Open in Angular

In my current situation, I have implemented a function in the first tab that displays a modal or component after 5 seconds: ngOnInit() { setTimeout(() => { this.openDialog(); }, 5000); } openDialog() { this.dialog.open(.....); } However, if ...

Resolving Unhandled Runtime Errors When Using Components with Dynamic API Calls in NextJS: A Guide to Fixing the Issue

As someone who is new to web development, I am currently working on a web app that makes use of the IGDB API (). The concept behind this website is allowing users to listen to game soundtracks and guess which game they belong to. For selecting a game, the ...

Switching Angular repository to download node_modules dependencies from internal company source: A step-by-step guide

Within my company, we have an internal artifactory where all the dependency libraries must be sourced from. It is not possible for me to download them from the internet using 'npm install'. Upon examining the package-lock.json file, I noticed th ...

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

Tips for utilizing the forEach method in Angular 2 without relying on ngFor?

I recently started learning Angular 2 and I am trying to figure out how to access array details using a forEach loop and apply certain conditions on it. Once I make the necessary changes, I want to display this data using ngFor. In Angular 1, this was ea ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

I am unable to utilize Local Storage within NextJS

type merchandiseProps = { merchandises: merchandiseType[]; cart?:string, collection?:string, fallbackData?: any }; const MerchandiseList: FC<merchandiseProps> = ({ merchandises }) => { const [cart, setCart] = useState<merchandiseType ...

CSS for Adjusting Parent Height Based on Child Content

I've been working on adjusting the height of the parent class to fit the child class perfectly without overflowing Here is a snippet from my CSS file: Parent &__video position: relative; width: 471px; background: red; border-radius: 12px ...

Display a "Loading" image in the gallery before anything else loads

Can a animated loading gif be implemented to load before the gallery images, or would it serve no purpose? The image will be loaded as a background using CSS. <link rel="stylesheet" href="loading.gif" /> Appreciate your help! ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

Conditional validation in Typescript based on the nullability of a field

I have come across the following code snippet: type DomainFieldDefinition<T> = { required?: boolean } type DomainDefinition<F, M> = { fields?: { [K in keyof F]: DomainFieldDefinition<F[K]> }, methods?: { [K in keyof M]: M[K] & ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...

Can we retrieve the CSS of an element?

Using Selenium's webdriverJS, I have automated tasks on an HTML5 page. To incorporate a CSS selector into a function, I had to rely on XPath for selecting elements: var complexXpath = "//*/div/a"; /* This is just an example */ var element = mydri ...