当前位置: 首页 > 知识库问答 >
问题:

图表js x轴日期时间格式化失败

潘自强
2023-03-14

我使用Python和Flask从服务和图表中获取数据。js可以绘制随时间变化的值。我无法在图表中使用xAxes时间格式。js。我是JavaScript新手,所以它可能很简单,比如缺少逗号,但我不这么认为。

我的python传递一个datetime对象到JavaScript。我想也许chart.js需要一个字符串,所以我创建了一个静态python函数来提供几个字符串日期,但它产生了相同的结果。

图表带有Jinja2模板的js脚本:

<head>
    <meta charset="utf-8" />
    <title>Chart.js Example</title>
    <!-- import plugin script -->
    <script src={{ url_for('static', filename="vendor/chart.min.js") }}></script>
    <script src={{ url_for('static', filename="vendor/moment.min.js") }}></script>
    <!--<script src='static/vendor/chart.min.js'></script>
    <link rel="stylesheet" href={{ url_for('static', filename="chartStyle.css") }}> -->

</head>
<body>
<h1>Simple Line Chart</h1>


<div class="container" style="position: relative; height:40vh; width:80vw">
    <canvas id="myChart"></canvas>
</div>
<div>
    <table>
        <tr>
            <th>DateTime</th>

        </tr>
        {% for itme in labels %}
            <tr><td>{{itme}}</td></tr>
            {% endfor %}
    </table>
</div>
 <script>
    var ctx = document.getElementById('myChart').getContext('2d');
    // define the chart data
    var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'line', //types: bar, horizontalBar, pie, line, doughnut, radar, polarArea

        // The data for our dataset
        data: {
            labels: [
                {% for item in labels %}
                    new Date('{{item}}'), //I've tried inserting a string instead of date object
                    //'{{item}}',
                {% endfor %}],
            datasets: [{
                label: '{{ legend }}',
                backgroundColor: 'rgba(255, 99, 132, 0)',
                borderColor: 'rgb(117, 4, 28)',
                borderWidth:1,
                hoverBorderWidth:3,
                hoverBorderColor:'#000',
                data: [{% for item in values %}
                    {{item}},
                {% endfor %}],
            }]
        },
        options:{
            title:{
                display:true,
                text:'test string date time',
                fontSize:25,
            },
            legend:{
                //display:false //to hide legend
                position:'right',
                labels:{
                    fontColor:'#000'
                }
            },
            tooltips:{
                //enabled:false,
            },
            scales:{
                yAxes:[{
                    scaleLabel:{
                        display: true,
                        labelString: 'mg/m3',
                        fontColor: '#000',
                        fontWeight: 'bold',
                        fontSize:25
                    }
                }],
                xAxes:[{
                    Type: 'time',
                    time: {
                        parser: 'HH:mm:ss a',   //these formatting values do nothing, I've tried a few different ones
                        unit: 'second',   //I have tried minutes and hours too, same result
                        displayFormats: {
                            'millisecond': 'HH:mm:ss a',   //I have tried without the 'a' too, same result
                            'second': 'HH:mm:ss a',
                            'minute': 'HH:mm:ss a',
                            'hour': 'HH:mm:ss a',
                            'day': 'HH:mm:ss a',
                            'week': 'HH:mm:ss a',
                            'month': 'HH:mm:ss a',
                            'quarter': 'HH:mm:ss a',
                            'year': 'HH:mm:ss a',
                        }
                    },
                    ticks: {
                        source: 'auto'
                    },
                    scaleLabel:{
                        display: true,
                        labelString: 'Recording Time',
                        fontColor: '#000',                        
                        fontWeight: 'bold',
                        fontSize:25
                }
                }]
            },
            responsive: true,
            maintainAspectRatio: false,
            elements: {
                point:{
                    radius: 0
                },
                line: {
                    tension: 0
                }
            },
        }

    });





</script>
</body>
</html>

带有测试数据的Python函数:

from flask import Flask, Blueprint, render_template, request
stringDate_bp5 = Blueprint('stringDate_bp5', __name__,
    template_folder='../templates',
    static_folder='../stringDate/static/vendor/', static_url_path='/stringDate/static/vendor/')


@stringDate_bp5.route("")
def stringDate():
    #reading1 = datetime.datetime(2019, 12, 19, 13, 36, 29, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
    labels = ['2019-12-19T13:36:29-08:00', '2019-12-19T13:36:59-08:00', '2019-12-19T13:37:29-08:00', '2019-12-19T13:37:59-08:00', '2019-12-19T13:38:29-08:00']
    values = [0.05, 0.07, 0.15, 0.08, 0.05]
    legend = 'Test String Dates'
    return render_template('chart2.html', values=values, labels=labels, legend=legend)

输出:

图表输出,包括日、月、日期、年、时间、UTC偏移量、时区。X轴标签应该只是时间,但是无论我尝试什么,标签都保持上面显示的默认格式。

共有1个答案

蓝飞
2023-03-14

Type:'time'更改为type:'time'后,您的图表配置看起来很好。您可以运行下面的版本,它替代您的Python模板变量。

这里还有一些其他的东西要检查

  • 纠正type错别字后,查找控制台错误。
  • 确保moment.js加载正确。
  • 检查moment.js和Chart.js的版本(下面的示例分别使用2.26.0和2.9.3)。
  • 提供实际的超文本标记语言源(而不是模板),因为如果它仍然损坏,它意味着模板/传递值有问题。
const config = {
  // The type of chart we want to create
  type: 'line', //types: bar, horizontalBar, pie, line, doughnut, radar, polarArea

  // The data for our dataset
  data: {
    labels: [new Date('2019-12-19T13:36:29-08:00'), new Date('2019-12-19T13:36:59-08:00'), new Date('2019-12-19T13:37:29-08:00'), new Date('2019-12-19T13:37:59-08:00'), new Date('2019-12-19T13:38:29-08:00')],
    datasets: [{
      label: 'Test String Dates',
      backgroundColor: 'rgba(255, 99, 132, 0)',
      borderColor: 'rgb(117, 4, 28)',
      borderWidth: 1,
      hoverBorderWidth: 3,
      hoverBorderColor: '#000',
      data: [0.05, 0.07, 0.15, 0.08, 0.05],
    }]
  },
  options: {
    title: {
      display: true,
      text: 'test string date time',
      fontSize: 25,
    },
    legend: {
      //display:false //to hide legend
      position: 'right',
      labels: {
        fontColor: '#000'
      }
    },
    tooltips: {
      //enabled:false,
    },
    scales: {
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'mg/m3',
          fontColor: '#000',
          fontWeight: 'bold',
          fontSize: 25
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          parser: 'HH:mm:ss a', //these formatting values do nothing, I've tried a few different ones
          unit: 'second', //I have tried minutes and hours too, same result
          displayFormats: {
            'millisecond': 'HH:mm:ss a', //I have tried without the 'a' too, same result
            'second': 'HH:mm:ss a',
            'minute': 'HH:mm:ss a',
            'hour': 'HH:mm:ss a',
            'day': 'HH:mm:ss a',
            'week': 'HH:mm:ss a',
            'month': 'HH:mm:ss a',
            'quarter': 'HH:mm:ss a',
            'year': 'HH:mm:ss a',
          }
        },
        ticks: {
          source: 'auto'
        },
        scaleLabel: {
          display: true,
          labelString: 'Recording Time',
          fontColor: '#000',
          fontWeight: 'bold',
          fontSize: 25
        }
      }]
    },
    responsive: true,
    maintainAspectRatio: false,
    elements: {
      point: {
        radius: 0
      },
      line: {
        tension: 0
      }
    },
  }

};

const ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>

<body>
  <canvas id="canvas" width="600" height="400"></canvas>
</body>
 类似资料:
  • 问题内容: 我试图用pyplot在x轴上的对象列表上绘制一些数据。但是日期以标准格式显示(太长)。我可以通过使用创建日期字符串列表来规避此问题,而改用它。我也知道,可以使用某种对象固有的对象代替。 但是,有没有一种方法可以显示对象的格式?无需将所有内容都转换为字符串或另一种对象? 谢谢。 问题答案: 您可以使用:

  • 主要内容:日期格式化符号,Python处理,Pandas处理当进行数据分析时,我们会遇到很多带有日期、时间格式的数据集,在处理这些数据集时,可能会遇到日期格式不统一的问题,此时就需要对日期时间做统一的格式化处理。比如“Wednesday, June 6, 2020”可以写成“6/6/20”,或者写成“06-06-2020。 日期格式化符号 在对时间进行格式化处理时,它们都有固定的表示格式,比如小时的格式化符号为 ,分钟简写为 ,秒简写为 。下表对常用的日期

  • 问题内容: 我有一个类似的日期/时间字符串,但我想将其转换为,我该怎么做? 我正在使用以下代码,但会引发异常。 问题答案: 您可以执行简单的字符串操作并创建js日期对象。请参见下面的函数,该函数接受// yyyy-mm-dd hh:mm:ss格式的日期

  • 我有一个以下格式的字符串: 我想利用这个时刻。js以这种格式获取它,用于显示。 我试着用这个方法, 哪些错误并表示没有称为“替换”的方法?我是不是走错了路? 我还应该提到,我正在使用一个预打包版本的矩。js,为Meteor打包。js 堆栈跟踪:

  • 下表显示可用于为图表中的日期时间字段创建用户定义的数据格式的说明符。 说明符 描述 D 将日显示为不带前导零的数字(1-31)。 DD 将日显示为带前导零的数字(01-31)。 M 将月份显示为不带前导零的数字(1-12)。 MM 将月份显示为带前导零的数字(01-12)。 MMM 将月份显示为缩写形式(Jan-Dec)。 MMMM 将月份显示为完整月份名(January-December)。 Y

  • 下表显示可用于为图表中的日期时间字段创建用户定义的数据格式的说明符。 说明符 描述 D 将日显示为不带前导零的数字(1-31)。 DD 将日显示为带前导零的数字(01-31)。 M 将月份显示为不带前导零的数字(1-12)。 MM 将月份显示为带前导零的数字(01-12)。 MMM 将月份显示为缩写形式(Jan-Dec)。 MMMM 将月份显示为完整月份名(January-December)。 Y

  • 下表显示可用于为图表中的日期时间字段创建用户定义的数据格式的说明符。 说明符 描述 D 将日显示为不带前导零的数字(1-31)。 DD 将日显示为带前导零的数字(01-31)。 M 将月份显示为不带前导零的数字(1-12)。 MM 将月份显示为带前导零的数字(01-12)。 MMM 将月份显示为缩写形式(Jan-Dec)。 MMMM 将月份显示为完整月份名(January-December)。 Y

  • 问题内容: 如何在AngularJS中正确显示日期和时间? 下面的输出同时显示输入和输出,带有和不带有AngularJS日期过滤器: 打印: 所需的显示格式为 或 问题答案: v.Dt可能不是Date()对象。 参见http://jsfiddle.net/southerd/xG2t8/ 但在您的控制器中: