【问题标题】:show more dataset than labels in chart.js在 chart.js 中显示比标签更多的数据集
【发布时间】:2021-08-01 23:00:14
【问题描述】:

感谢您的宝贵时间。

我想做这个,你可以在图片中看到。

chartJs line graph

我有数组中标签的值和其他数组中 yAxes 的值。 标签显示一小时的 59 分钟,我只想显示分钟(05、10、15、20 ......等) 我只能在这个时间值中推入数组,但是当我将“时间”放在chartjs中的标签中时,图表只在yAxes中显示12个值,我想在yAxes中显示59个值并且只显示这个xAxes。 ..

如果我这样做:

  import { Fragment } from "react";
  import { Line } from "react-chartjs-2";
 import "./GraficosDemo.css";

const GraficosDemo = ({ datosMeteoGraf, rotuloGrafico }) => {
var colors = [
"#007bff",
"#0097fc",
"#333333",
"#c3e6cb",
"#dc3545",
"#ed872d",
];
if (!datosMeteoGraf) return null;

const dataSetTWS = [];
const dataSetTWS_GUST = [];
const minutos = [];

 //GRAFICO DE INTENSIDAD DE VIENTO
  for (let i = 0; i < datosMeteoGraf.length; i++) {    
    dataSetTWS.push(datosMeteoGraf.TWS[i]);    
     }

 //GRAFICO DE INTENSIDAD DE RACHAS DE VIENTO
   for (let i = 0; i < datosMeteoGraf.length; i++) {    
     dataSetTWS_GUST.push(datosMeteoGraf.TWS_GUST[i]);  
   }
    // console.log(dataSetTWS_GUST);

    for (let i = 0; i < datosMeteoGraf.length; i++) {         
     if((new Date (datosMeteoGraf.TIME[i]).getMinutes()) % 5 === 0){
  minutos.push(new Date(datosMeteoGraf.TIME[i]).toTimeString().slice(0, 5))
   }        
   }


  return (
    <Fragment>
      <Line
        data={{
       labels: minutos,
      datasets:[
        {
          borderWidth: 0,
          label: "Intensidad Última Hora",
          data: dataSetTWS,
          backgroundColor: "transparent",
          borderColor: colors[1],
          pointStyle: "dash",
        },          
        {
          borderWidth: 0,
          label: "Intensidad Rachas de Viento",
          data: dataSetTWS_GUST,
          backgroundColor: "transparent",
          borderColor: colors[4],
          pointStyle: "dash",
        },
      ],
    }}
    height={250}
    options={{
      maintainAspectRatio: false,
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
              stepSize: 1,
            },
          },
        ],
        xAxes: [
          {
            display:true,
          }
        ]
      },
    }}
  />

  
</Fragment>
  );
 };

export default GraficosDemo;

我有这个:

push in time array only the minutes multiples of 5

但我想保留我的所有价值观并只显示这些标签。就像顶部的图片一样。

有人可以帮帮我吗? 谢谢

【问题讨论】:

  • 如果你能得到答案,你能接受吗?

标签: javascript chart.js react-chartjs


【解决方案1】:

Chart.js 需要标签来映射值,因此您需要提供标签,尽管您可以使用 tick 回调来隐藏一些标签,如下所示:

var options = {
  type: 'line',
  data: {
    labels: ["0", "5", "10", "15", "20", "25"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          callback: (tick) => (Number(tick) % 10 === 0 ? tick : null) // Replace null with "" to show gridline
        }
      }]
    }
  }
}

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.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

【讨论】:

    【解决方案2】:

    ChartJS 不需要需要标签来映射值。做你正在做的事情的好方法是实现时间轴。这将允许您添加任何时间范围,而无需添加到标签列表中。您还需要一个时间解析器。 here is a list.

    配置:

    const config = {
      type: 'line',
      data: data,
      options: { 
          scales: {
              xAxis: {
                    type: 'time',
                    
                    ticks: {
                        source: 'labels', // get ticks from given labels
                    },
    
                    time: {
                        minUnit: 'minute', // smallest time format
    
                        displayFormats: {
                            minute: "HH:mm",
                            hour: "dd/MM HH:mm",
                            day: "dd/MM",
                            week: "dd/MM",
                            month: "MMMM yyyy",
                            quarter: 'MMMM yyyy',
                            year: "yyyy",
                        }
                    }
                },
            },
        }
    };
    

    数据:

    var data = {
      labels: labels,
      datasets: [{
        label: 'My First Dataset',
        data: generateTestSeries(),
        fill: false,
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
      }]
    };
    

    标签:

    var labels = [
      new Date(2021, 10, 15, 15, 0),
      new Date(2021, 10, 15, 15, 5),
      new Date(2021, 10, 15, 15, 10),
      new Date(2021, 10, 15, 15, 15),
      new Date(2021, 10, 15, 15, 20),
      new Date(2021, 10, 15, 15, 25),
      new Date(2021, 10, 15, 15, 30),
      new Date(2021, 10, 15, 15, 35),
      new Date(2021, 10, 15, 15, 40),
      new Date(2021, 10, 15, 15, 45),
      new Date(2021, 10, 15, 15, 50),
      new Date(2021, 10, 15, 15, 55),
      new Date(2021, 10, 15, 16, 0),
    ];
    

    测试数据:

    function generateTestSeries () { // create test data
        let series = [];
        var val = 0;
    
        let start = new Date(2021, 10, 15, 15);
        let end = new Date(2021, 10, 15, 16);
    
        while (start < end) {
            val += Math.floor(Math.random() * 11) - 5;
    
            series.push({
                "x": start, 
                "y": val, 
            });
    
            start = new Date(start.getTime() + 60000);
        }
        
        return series;
    }
    

    这看起来像:

    至于我之前关于标签的观点,您可以删除它们,它会根据您的数据生成一些。它看起来像这样:

    如果没问题,您可以通过删除 labels: labels, 来做到这一点

    并将source: 'labels', 更改为source: 'auto',

    有关时间轴的更多信息:Time Cartesian Axis

    【讨论】:

    • 如果 chart.js 不需要标签来将值映射到为什么要使用标签来映射值而不是仅提供数据数组?
    • @LeeLenalee 第一张图有标签,第二张图没有标签。第一个更可定制,第二个更容易制作和更灵活。
    • 两者都使用标签,唯一的区别是在第一个图表中,您在标签数组中提供它们,而在第二个图表中,您将它们作为对象提供,其中 X 是标签,Y 是值
    • 就像你说的那样,我应该只能传递一个数字数组,但是 chart.js 将不知道如何处理这些数字,所以你如何放置它并不重要 chartjs需要标签来将值映射到并可视化它们
    • @LeeLenalee 我想更好的措辞应该是“你不必给标签。”如果source: auto 在后台根据我的数据创建标签,我真的不在乎。我不必与他们打交道,这对我来说很重要。
    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2016-09-09
    • 2017-08-21
    相关资源
    最近更新 更多