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

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...

How to create centered striped backgrounds in CSS

Attempting to achieve a background similar to the one shown Can this be accomplished using CSS? ...

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...

NativeScript Error Code NG8001: Element 'ActionBar' is unrecognized

In my project, the startupscreen module setup is as follows: import { NativeScriptFormsModule } from "@nativescript/angular"; import { NativeScriptCommonModule } from "@nativescript/angular/common"; import { NgModule, NO_ERRORS_SCHEMA } ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

Steadfast item securely fastened to its guardian

How can I ensure a fixed object within a relatively positioned parent is clipped to its parent's boundaries as it moves with scrolling down the page? I have been trying to find a solution for this issue, but haven't had any luck so far. ...

Adjust image placement when resizing the window or rotating a mobile device

When the window is maximized or the phone is in portrait position, the magnifying glass stays in its place. However, when I resize the window or rotate the mobile phone, the position of the magnifying glass changes. I've tried using different units ...

Requesting Next Page via Angular GET Method for Paginated API

Having trouble loading data from a paginated REST API using the code below. Any suggestions for a better approach are welcome! component.ts import { Component, OnInit } from '@angular/core'; import {HttpClient} from '@angular/common/http&a ...

Ionic: Implementing a clear text field function when the ion-back-button is clicked

So I've created a feature where users can scan product barcodes using BarcodeScanner. Once the barcode is scanned, the product ID appears in a text field and is then sent to another page where an API call is made to display product details. On this pr ...

Simulate an HTTP request from a service class during a jasmine test

I initially believed that spying on services in Jasmine using the spyOn method and returning a value when the method is called was straightforward. However, it seems like my assumption may have been too simplistic? I intend to test the following action in ...

What is the significance of `new?()` in TypeScript?

Here is a snippet of code I'm working with in the TypeScript playground: interface IFoo { new?(): string; } class Foo implements IFoo { new() { return 'sss'; } } I noticed that I have to include "?" in the interface met ...

Issue encountered when populating FormArray with a FormGroup inside a loop in Angular version 17

Encountering an error while trying to populate a FormArray in Angular (version 17): Issue arises at line 44 with the error message: Argument of type 'FormGroup<{ name: FormControl<string | null>; amount: FormControl<number | null>; }&g ...

Tips for adding an extensive collection of fixed attributes to a function using Typescript

I am attempting to write a function that includes a lengthy list of static strings attached as properties, all returning the property as a string value: const arr = ["a", "b", "c"]; // there are around 140 items in the actual list const f = (tag: strin ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

What is the process for converting a .ts file to a .js file within a Next.js project for Web worker implementation?

I am currently working on a TypeScript Next.js project: "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint& ...

What is the best way to integrate qrcode-generator into an Angular 2 application?

I've been trying to implement the qrcode-generator in my app without success, even though it works in plunker. In my app, I am using angular-cli and angular 2.rc-1. Here are the steps to reproduce: ng new newAppName cd newAppName ng serve It work ...

What is the proper way to select the <ul> element within an FTL template?

Can someone provide guidance on how to target a <ul> container within a freemarker template using JavaScript? My goal is to display the content of this specific <ul> element in my FreeMarker template on the web page. Any suggestions on how I ...

What is preventing my div from reaching 100% height when I implement an HTML5 doctype? Is there a solution to achieving a full height div?

I'm currently working on organizing the layout for a basic gallery webapp, and I've encountered an issue where some of my divs are shrinking in height when using an HTML5 doctype declaration. Despite trying different CSS properties, I can't ...

Using WebDriver Selenium to choose an element within a table following another element

The webpage features a user details table with a functionality to delete users. To remove a user, I must select the row based on the username and then click the "Delete" button. The structure of the HTML table is as follows: <table id="tblUsersGrid" ce ...

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...