具有对应于每个条的图例的ChartJS条形图 [英] ChartJS bar chart with legend which corresponds to each bar

查看:46
本文介绍了具有对应于每个条的图例的ChartJS条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解其条形图上的ChartJS文档。这对我来说没有任何意义,因为顶部的标签看起来好像只适用于第一个条(基于颜色),换句话说,整个图表(它是唯一的标签)

I'm trying to understand the ChartJS documentation on their bar chart. It doesn't make a log of sense to me as the label at the top in once sense looks as though it applies to just the first bar (based on color) and in another sense, the entire chart (it is the only label that's not in a tooltip and it is front and center)

我一直在努力使其更像他们的折线图,该折线图显示了带有图例的图例以及与图表上每条线相关的彩色正方形。 (他们没有多线图的示例,但确实如此)。

I've been struggling to make it more like their line chart, which shows a legend with a label and a colored square related to each line on the chart. (they haven't got an example of a multiline chart, but it does work like this).

数据对象中的labels属性被转换为旁边的值条形,例如标签:['36%','10%','18%','34%','0%','2%']

The labels property within the data object gets translated to the value next to the bar, eg labels: ['36%', '10%', '18%', '34%', '0%', '2%']

我想在顶部添加一个图例,以表明淡绿色是苹果,灰色是橙色,绿色是梨子,等等,但是我最接近的是提供 data.datasets 对象数组并制作标签和数组,这只会导致成组的条形,例如示例此处

I want a legend at the top that indicates the aqua color is apples, the grey is oranges, the green is pears, etc, but the closest I've come is providing data.datasets an array of objects and making labels and array, which only results in groups of bars, like the example here.

推荐答案

做到这一点的方法是,在数据集中创建多个项目,每个项目仅具有一个类别的数据。您可以拥有一个称为stock的顶级标签,然后为每种类型创建单独的数据集。

The way to do this, to create multiple items in the datasets, each having data for only one category. You can have one top level label called stock and then create the individual data-sets for each type.

// create a chart.
const ctx = canvas.getContext("2d");
const chart = new Chart(ctx, {
   type: "horizontalBar",
   data: {
      labels: ["Stock"],
      datasets: [{
         label: "Apples",
         backgroundColor: "#AF7",
         data: [Math.random() * 100],
      },{
         label: "Oranges",
         backgroundColor: "#FA4",
         data: [Math.random() * 100],
      },{
         label: "Mangos",
         backgroundColor: "#FF7",
         data: [Math.random() * 100],
      },{
         label: "Avocados",
         backgroundColor: "#2A7",
         data: [Math.random() * 100],
      }]
   },
   options: {
          responsive: false,
          legend: { position: 'top'},
          title: { display: true, text: 'Fruit in stock'}
      }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id=canvas height=200 width=500></canvas>

这篇关于具有对应于每个条的图例的ChartJS条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆