【问题标题】:Add the year in the x-axis in Matlab在 Matlab 的 x 轴上添加年份
【发布时间】:2016-03-27 07:04:30
【问题描述】:

我有一个包含mmyyyySPI(标准化降水指数)变量的两列数据。前两个样本没有数据 (NAN)。文件是:

011982 NAN
021982 NAN
031982 -1.348
.
.
.
122013 1.098

我将时间和 SPI 数据加载到 MATLAB 中,然后我想绘制它,但它不起作用。

我想绘制折线图,​​但我真的不知道如何在 x 轴上绘制时间,我希望我的 x 轴只显示年份。

【问题讨论】:

  • @Amro 我听从了你的建议,但我得到了“使用 textscan 格式错误的格式字符串时出错”。我该怎么办?非常感谢您的帮助...
  • 您运行的是哪个版本的 MATLAB?就像我在回答中提到的那样,datetime 的东西只在最近的版本中添加了
  • @Amro 我用的是 Matlab R2014a 版本
  • 好的,我添加了另一个适用于所有 MATLAB 版本的解决方案。
  • @Armo 非常感谢你hh

标签: matlab datetime plot


【解决方案1】:

在 MATLAB 中使用新的 datetime 数据类型(在 R2014b 中添加),这应该很容易。

这是一个例子。首先我们将数据加载到 MATLAB table

% import data from file
fid = fopen('file.dat', 'rt');
C = textscan(fid, '%{MMyyyy}D %f');
fclose(fid);

% create table
t = table(C{:}, 'VariableNames',{'date','SPI'});

你会得到这样的东西:

>> t(1:10,:)
ans = 
     date       SPI   
    ______    ________
    011982         NaN
    021982         NaN
    031982       2.022
    041982      1.5689
    051982     0.75813
    061982    -0.74338
    071982     -1.7323
    081982     -2.4466
    091982    -0.86604
    101982    0.085698

plot the data with date and time旁边,就像拨打plot一样简单:

plot(t.date, t.SPI)
xlabel('Date'), ylabel('Standardized Precipitation Index')

默认情况下,plot 根据数据范围选择刻度线位置。当您放大和缩小绘图时,刻度标签会自动调整到新的轴范围。

但如果您愿意,也可以为 datetime 刻度标签指定 custom format。请注意,执行此操作时,绘图始终根据指定值格式化刻度标签,它们不会在缩放时调整:

plot(t.date, t.SPI, 'DatetimeTickFormat','yyyy')

【讨论】:

    【解决方案2】:

    我正在添加另一个适用于没有 tabledatetime 数据类型的旧 MATLAB 版本的答案。

    和以前一样,我们首先从文件中导入数据,但这次我们将日期读取为字符串,然后使用datenum 函数将它们转换为序列日期数字(定义为自“0000 年 1 月 0 日”):

    % import data from file
    fid = fopen('file.dat', 'rt');
    C = textscan(fid, '%s %f');
    fclose(fid);
    
    % create matrix
    t = [datenum(C{1},'mmyyyy') C{2}];
    

    数据如下:

    >> format long 
    >> t(1:10,:)
    ans =
       1.0e+05 *
       7.239120000000000                 NaN
       7.239430000000000                 NaN
       7.239710000000000   0.000005606888474
       7.240020000000000   0.000009156147863
       7.240320000000000   0.000004504804864
       7.240630000000000   0.000008359005819
       7.240930000000000   0.000007436313932
       7.241240000000000   0.000002800134237
       7.241550000000000   0.000005261613664
       7.241850000000000   0.000001809901372
    

    接下来我们像以前一样绘制数据,但我们使用 datetick 函数将 x 轴格式化为日期('yyyy' 表示年份):

    plot(t(:,1), t(:,2))
    datetick('x', 'yyyy')
    xlabel('Date'), ylabel('Standardized Precipitation Index')
    

    很遗憾,当您放大和缩小时,刻度标签不会自动更新...好消息,File Exchange 上有解决此问题的解决方案,例如 datetickzoomdatetick2

    猜你喜欢
    • 1970-01-01
    • 2014-03-23
    • 2016-03-19
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多