创建不使用模板的自定义报告器
此示例说明如何创建不使用模板文件的报告器。大多数报告器使用的模板包含用于静态内容的预定义节和用于动态内容的空位。您通过创建内容并指定分配的空位来填补空位。要创建使用模板的自定义报告器,请使用 mlreportgen.report.Reporter.customizeReporter 方法。
您还可以创建无需定义模板即可生成所有内容的报告器,而不必使用基于模板的报告器。在此示例中,您将定义一个报告器,该报告器使用 MATLAB® 代码动态生成其所有内容。
打开报告器
打开 WeeklyTempReport 类定义文件。为了自动生成内容,此报告器重新定义了 getImpl 方法。当您将 Reporter 子类追加到报告时,报告器会自动调用 getImpl。在此示例中,WeeklyTempReport 自定义报告器重新定义了 getImpl,使该方法创建高温和低温绘图,然后使用 Figure 报告器创建绘图的快照图像。
function impl = getImpl(obj, rpt)
import mlreportgen.dom.*
% Create the plot with high temperature data
f = figure;
x = 1:7;
barWidth=0.5;
bar(x,obj.HighTemps,barWidth,FaceColor=[0.2 0.2 0.5]);
% Plot the low temperatures as a second bar graph over the
% first bar graph
hold on
barWidth = 0.25;
bar(x,obj.LowTemps,barWidth,FaceColor=[0 0.7 0.7])
hold off
% Add y axis label and a legend
grid on
ylabel("Temperature (\circF)")
legend(["Daily High", "Daily Low"],Location="northwest")
% Add tick labels for the days of the week
ax = gca;
ax.XTick = 1:7;
weekStart = obj.StartDate;
weekStart.Format = "eeee";
ax.XTickLabels = string([weekStart, weekStart+1, ...
weekStart+2, weekStart+3, weekStart+4, ...
weekStart+5, weekStart+6]);
ax.XTickLabelRotation = 45;
% Add a title
weekStart.Format = "MMMM d";
titleStr = "Weather Forecast for "+string(weekStart) + ...
" - "+string(weekStart+6);
title(titleStr);
% Get a snapshot of the plot using the Figure reporter
figRptr = mlreportgen.report.Figure(f);
snapshotImagePath = figRptr.getSnapshotImage(rpt);
% Return a DOM Image object with the snapshot
impl = Image(snapshotImagePath);
impl.Style = [impl.Style, {ScaleToFit}];
% Close the figure after getting the snapshot
close(f);
end
生成报告
此代码创建一个报告,使用自定义报告器生成温度图,然后将该图追加到报告中。
import mlreportgen.report.* import mlreportgen.dom.* % Create example weather data. highTemps = [48 55 58 63 67 71 67]; lowTemps = [43 47 46 48 51 55 54]; % Create document rpt = Report("test"); % Create reporter to display the predicted % high and low temperatures for this week rptr = WeeklyTempReporter(highTemps, lowTemps); append(rpt, rptr); close(rpt); rptview(rpt);
您可以像使用其他内置 MATLAB Report Generator™ 报告器和基于模板的自定义报告器一样使用此报告器。