te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Change ChartJs axis title dynamically - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change ChartJs axis title dynamically - Stack Overflow

programmeradmin3浏览0评论

I've created a chart like this

if (userLanguageCode === "es") {
    customTooltipFormat = 'DD/MM/YYYY, HH:mm:ss';

    customDisplayFormats = {
        'millisecond': 'SSS [ms]',
        'second': 'HH:mm:ss', // 11:20:01 AM
        'minute': 'D/MM/YY HH:mm', // 11:20:01 AM
        'hour': 'D/MM/YY HH[h]', // Sept 4, 5PM
        'day': 'D/MM/YYYY', // Sep 4 2015
        'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
        'month': 'MMM YYYY', // Sept 2015
        'quarter': '[Q]Q - YYYY', // Q3
        'year': 'YYYY', // 2015
    };
}

Chart.defaults.global.responsive = true;
Chart.defaults.global.animation = false;

datosChartHistoricos =  {
    labels: [],
    datasets: [{
        label: textoValor,
        backgroundColor: "rgba(0,181,255,0.5)",
        fill: chartWithIncrementValues? true: false,
        borderColor: "rgba(0,192,192,1)",
        pointBorderColor: "rgba(0,181,255,1)",
        pointBackgroundColor: "rgba(255,255,255,1)",
        pointBorderWidth: 1,
        data: []
    }]
};

var ctx = document.getElementById("grafica").getContext("2d");
chartHistoricos = new Chart(ctx, {
    type: chartWithIncrementValues? "bar" : "line",
    data: datosChartHistoricos,
    options: {
        responsive: true,
        elements: {
            rectangle: {
                borderWidth: 1,
                borderColor: 'rgb(0, 0, 0)',
                borderSkipped: 'bottom'
            }
        },
        scales: {
            xAxes: [{
                type: "time",
                time: {
                    tooltipFormat: customTooltipFormat,
                    displayFormats: customDisplayFormats,
                }
            }, ],
            yAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: textoValor + " (" + unidadesValor + ")"
                }
            }]
        },
        legend: {
            display: false,
        }
    }
});

This is the default config for the chart, data is added dynamically, but the user can choose different data values to show, like temperature, distance... To do this, I just change the data value of the dataset and the label, but I can't figure how to change the yAxis label using javascript when I change the dataset value. Initialization title is ok.

Any tips?

Thanks!

I've created a chart like this

if (userLanguageCode === "es") {
    customTooltipFormat = 'DD/MM/YYYY, HH:mm:ss';

    customDisplayFormats = {
        'millisecond': 'SSS [ms]',
        'second': 'HH:mm:ss', // 11:20:01 AM
        'minute': 'D/MM/YY HH:mm', // 11:20:01 AM
        'hour': 'D/MM/YY HH[h]', // Sept 4, 5PM
        'day': 'D/MM/YYYY', // Sep 4 2015
        'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
        'month': 'MMM YYYY', // Sept 2015
        'quarter': '[Q]Q - YYYY', // Q3
        'year': 'YYYY', // 2015
    };
}

Chart.defaults.global.responsive = true;
Chart.defaults.global.animation = false;

datosChartHistoricos =  {
    labels: [],
    datasets: [{
        label: textoValor,
        backgroundColor: "rgba(0,181,255,0.5)",
        fill: chartWithIncrementValues? true: false,
        borderColor: "rgba(0,192,192,1)",
        pointBorderColor: "rgba(0,181,255,1)",
        pointBackgroundColor: "rgba(255,255,255,1)",
        pointBorderWidth: 1,
        data: []
    }]
};

var ctx = document.getElementById("grafica").getContext("2d");
chartHistoricos = new Chart(ctx, {
    type: chartWithIncrementValues? "bar" : "line",
    data: datosChartHistoricos,
    options: {
        responsive: true,
        elements: {
            rectangle: {
                borderWidth: 1,
                borderColor: 'rgb(0, 0, 0)',
                borderSkipped: 'bottom'
            }
        },
        scales: {
            xAxes: [{
                type: "time",
                time: {
                    tooltipFormat: customTooltipFormat,
                    displayFormats: customDisplayFormats,
                }
            }, ],
            yAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: textoValor + " (" + unidadesValor + ")"
                }
            }]
        },
        legend: {
            display: false,
        }
    }
});

This is the default config for the chart, data is added dynamically, but the user can choose different data values to show, like temperature, distance... To do this, I just change the data value of the dataset and the label, but I can't figure how to change the yAxis label using javascript when I change the dataset value. Initialization title is ok.

Any tips?

Thanks!

Share Improve this question edited Mar 7, 2017 at 10:13 Rubén M asked Mar 7, 2017 at 9:39 Rubén MRubén M 1191 gold badge1 silver badge14 bronze badges 2
  • Using firebug to debug the web page. With console.log(chartHistoricos) I can see all the objects I can access, but there is no "labelString" inside axes objects... – Rubén M Commented Mar 7, 2017 at 10:12
  • Quite old but I ran into a similar issue. On the console not everything was visible. But in the code some stuff was available. – Kaspatoo Commented Jan 31, 2023 at 22:38
Add a ment  | 

2 Answers 2

Reset to default 11

You can change the scale title simply by updating the labelString value in your chart object's options property and calling the .update() prototype method.

Assuming I have a chart instance called myBar (the instance is what is returned from the Chart.js constructor), then I can use the below example to change the y-axes title.

myBar.options.scales.yAxes[0].scaleLabel.labelString = "My New Title";
myBar.update();

Here is a codepen that demonstrates a working example of this. Just click on the "Change Title" button to see if work.

in V3 the scales have changed so every scale is its own object, to get jordanwillis answer to work you will need to change it to:

myBar.options.scales.y.title.text = 'New title';
myBar.update();

But you can also use scriptable options which update automatically when the chart gets redrawn so you can do it internally in the options object itself:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      },

      {
        label: '# of People',
        data: [3, 1, 9, 3, 7, 4],
        borderColor: 'lightBlue'
      }
    ]
  },
  options: {
    scales: {
      y: {
        title: {
          display: true,
          text: (ctx) => {
            const chart = ctx.scale.chart;
            const chartStatus = chart.data.datasets.map((e, i) => (!!chart.getDatasetMeta(i).hidden));

            if (chartStatus.every(e => e === false)) {
              return 'no datasets hidden'
            } else if (chartStatus.every(e => e === true)) {
              return 'all datasets hidden'
            } else {
              let ret = chartStatus.reduce((acc, curr, i) => {
                if (curr) {
                  acc += ` ${i},`
                }

                return acc;
              }, chartStatus.indexOf(true) === chartStatus.lastIndexOf(true) ? 'dataset:' : 'datasets:')

              ret = ret.substring(0, ret.length - 1)
              ret += ' hidden'
              return ret
            }
          }
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare./ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

发布评论

评论列表(0)

  1. 暂无评论