Create a Custom Reporter Without a Template
This example shows how to create a reporter that does not use a template file. Most reporters use templates that include predefined sections for static content and holes for dynamic content. You fill the holes by creating the content and specifying the assigned hole. To create custom reporters that use templates, use the mlreportgen.report.Reporter.customizeReporter method.
Rather than using a template-based reporter, you can create a reporter that generates all of the content without having to define a template. In this example, you define a reporter that generates all of its content dynamically by using MATLAB® code.
Open the Reporter
Open the WeeklyTempReport class definition file. To automatically generate the content, this reporter redefines the getImpl method. When you append a Reporter subclass to a report, the reporter automatically invokes getImpl. In this example, the WeeklyTempReport custom reporter redefines getImpl so that the method creates a plot of high and low temperatures, then uses the Figure reporter to create a snapshot image of the plot.
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
Generate Report
This code creates a report, generates a temperature plot by using the custom reporter, and appends the plot to the report.
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);
You can use this reporter in the same way as other built-in MATLAB Report Generator™ reporters and template-based custom reporters.