2

我有带有“react-chartjs-2”的条形图,我应该将我的字体系列放在xAxes中的图表标签的位置:这种方式:(无效)

<Bar
    data={chartData}
    options={{ defaults: { global: { defaultFontFamily:"iransans} }}}
/>

这种方式不起作用:

    <Bar
        data={chartData}
        options={{ font: { family: "iransans" }}}
    />

有没有人知道这个???

4

3 回答 3

3

如果您使用的是 chart.js 3.x+,请参考以下代码以更改刻度、工具提示和图例的字体:

    // inside data.js(or your own data file)
 
    const options = {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: true,
          labels: {
            color: "rgb(255, 99, 132)",
            font: {
              family: "Montserrat" // Add your font here to change the font of your legend label
            }
          },
          tooltip: {
            bodyFont: {
              family: "Montserrat" // Add your font here to change the font of your tooltip body
            },
            titleFont: {
              family: "Montserrat" // Add your font here to change the font of your tooltip title
            }
          }
        }
      },
      tooltips: {
        backgroundColor: "#f5f5f5",
        titleFontColor: "#333",
        bodyFontColor: "#666",
        bodySpacing: 4,
        xPadding: 12,
        mode: "nearest",
        intersect: 0,
        position: "nearest"
      },
      scales: {
        yAxes: {
          barPercentage: 1.6,
          grid: {
            display: false,
            color: chartLineColor,
            zeroLineColor: "transparent"
          },
          ticks: {
            suggestedMin: 0,
            suggestedMax: 125000,
            padding: 2,
            backdropPadding: 2,
            backdropColor: "rgba(255,255,255,1)",
            color: chartLineColor,
            font: {
              family: "Montserrat", // Add your font here to change the font of your y axis
              size: 12
            },
            major: {
              enable: true
            }
          }
        },
        xAxes: {
          barPercentage: 1.6,
          grid: {
            display: false,
            zeroLineColor: "transparent"
          },
          ticks: {
            padding: 20,
            color: chartLineColor,
            font: {
              family: "Montserrat", // Add your font here to change the font of your x axis
              size: 12
            },
    
            major: {
              enable: false
            }
          }
        }
      }
    };

在您的反应组件内部:

import {someData,options} from './data.js'
function SomeComponent{
   return(
       <>
        <Line data={someData} options={options} />
       </>
     )
}

希望这很有用。如需进一步参考,请参阅本文

于 2021-10-07T06:25:37.617 回答
2

所以在看到github上的帖子后,这种方式奏效了:首先导入默认值:

import { defaults } from 'react-chartjs-2';

然后在某处设置这样的字体:

defaults.font.family = 'font name...';
于 2021-05-09T13:23:07.673 回答
0

回答上面的作品。只是为了看看你实际在做什么,你可以

console.log(defaults)

您会看到可以更改的全局变量列表。你也可以试试

console.log(defaults.font.family);

于 2021-06-16T23:01:15.470 回答