DUNE-DAQ
DUNE Trigger and Data Acquisition software
Loading...
Searching...
No Matches
trgtools.plot.PDFPlotter.PDFPlotter Class Reference

Public Member Functions

None __init__ (self, str save_name)
 
PdfPages get_pdf (self)
 
None plot_histogram (self, np.ndarray data, dict plot_details_dict)
 
None plot_errorbar (self, np.ndarray x_data, np.ndarray y_data, dict plot_details_dict)
 
None close (self)
 

Protected Member Functions

None _check_title_and_labels (self, plot_details_dict)
 

Protected Attributes

 _pdf = PdfPages(save_name)
 

Static Protected Attributes

tuple _DEFAULT_FIG_SIZE = (6, 4)
 
 _DEFAULT_HIST_STYLE
 
 _DEFAULT_ERRORBAR_STYLE
 

Detailed Description

Plotter with common plots to put on a single PDF.

Using this class requires the matplotlib module.
It creates a PdfPages object for shared plot saving
and has a few common plots that can be used.

The common plots take a dictionary of plot identifiers,
such as title, xlabel, and ylabel, and a sub-dictionary
that is used for modifying the style of the plots.

Plotting methods require a 'title', 'xlabel', and 'ylabel'
is within the passed plotting style dictionary. An error is
raised if any of the three are missing.

Definition at line 10 of file PDFPlotter.py.

Constructor & Destructor Documentation

◆ __init__()

None trgtools.plot.PDFPlotter.PDFPlotter.__init__ ( self,
str save_name )
Inits the PdfPages with the given :save_name:.

Parameters:
    save_name (str): Initializes the PdfPages object to save to with the given name.

Returns:
    Nothing.

Definition at line 45 of file PDFPlotter.py.

45 def __init__(self, save_name: str) -> None:
46 """
47 Inits the PdfPages with the given :save_name:.
48
49 Parameters:
50 save_name (str): Initializes the PdfPages object to save to with the given name.
51
52 Returns:
53 Nothing.
54 """
55 if save_name.endswith('.pdf'):
56 self._pdf = PdfPages(save_name)
57 else:
58 self._pdf = PdfPages(f"{save_name}.pdf")
59
60 return None
61

Member Function Documentation

◆ _check_title_and_labels()

None trgtools.plot.PDFPlotter.PDFPlotter._check_title_and_labels ( self,
plot_details_dict )
protected
Check that the given :plot_details_dict: contains a title
and labels.

Parameter:
    plot_details_dict (dict): Dictionary containing details on plotting styles.

Raises an error if missing.

Definition at line 62 of file PDFPlotter.py.

62 def _check_title_and_labels(self, plot_details_dict) -> None:
63 """
64 Check that the given :plot_details_dict: contains a title
65 and labels.
66
67 Parameter:
68 plot_details_dict (dict): Dictionary containing details on plotting styles.
69
70 Raises an error if missing.
71 """
72 if 'title' not in plot_details_dict:
73 raise KeyError("Missing 'title' in plot_details_dict!")
74 if 'xlabel' not in plot_details_dict:
75 raise KeyError("Missing 'xlabel' in plot_details_dict!")
76 if 'ylabel' not in plot_details_dict:
77 raise KeyError("Missing 'ylabel' in plot_details_dict!")
78
79 return None
80

◆ close()

None trgtools.plot.PDFPlotter.PDFPlotter.close ( self)
Close the PdfPages object.

Definition at line 204 of file PDFPlotter.py.

204 def close(self) -> None:
205 """
206 Close the PdfPages object.
207 """
208 self._pdf.close()
209 return

◆ get_pdf()

PdfPages trgtools.plot.PDFPlotter.PDFPlotter.get_pdf ( self)
Returns the PdfPages object.

This is useful for appending plots that are outside of this class.

Definition at line 81 of file PDFPlotter.py.

81 def get_pdf(self) -> PdfPages:
82 """
83 Returns the PdfPages object.
84
85 This is useful for appending plots that are outside of this class.
86 """
87 return self._pdf
88

◆ plot_errorbar()

None trgtools.plot.PDFPlotter.PDFPlotter.plot_errorbar ( self,
np.ndarray x_data,
np.ndarray y_data,
dict plot_details_dict )
Plot a scatter plot for the given x and y data to the PdfPages object.

Parameters:
    x_data (np.ndarray): Array to use as x values.
    y_data (np.ndarray): Array to use as y values.
    plot_details_dict (dict): Dictionary with keys such as 'title', 'xlabel', etc.

Returns:
    Nothing. Mutates :self._pdf: with the new plot.

Error bars are handled by :plot_details_dict: since they are a style
choice.

Definition at line 167 of file PDFPlotter.py.

171 plot_details_dict: dict) -> None:
172 """
173 Plot a scatter plot for the given x and y data to the PdfPages object.
174
175 Parameters:
176 x_data (np.ndarray): Array to use as x values.
177 y_data (np.ndarray): Array to use as y values.
178 plot_details_dict (dict): Dictionary with keys such as 'title', 'xlabel', etc.
179
180 Returns:
181 Nothing. Mutates :self._pdf: with the new plot.
182
183 Error bars are handled by :plot_details_dict: since they are a style
184 choice.
185 """
186 self._check_title_and_labels(plot_details_dict)
187
188 plt.figure(figsize=plot_details_dict.get('figsize', self._DEFAULT_FIG_SIZE))
189
190 errorbar_style = plot_details_dict.get('errorbar_style', self._DEFAULT_ERRORBAR_STYLE)
191 plt.errorbar(x_data, y_data, **errorbar_style)
192
193 plt.title(plot_details_dict['title'])
194 plt.xlabel(plot_details_dict['xlabel'])
195 plt.ylabel(plot_details_dict['ylabel'])
196
197 plt.legend()
198
199 plt.tight_layout()
200 self._pdf.savefig()
201 plt.close()
202 return None
203

◆ plot_histogram()

None trgtools.plot.PDFPlotter.PDFPlotter.plot_histogram ( self,
np.ndarray data,
dict plot_details_dict )
Plot a histogram onto the PdfPages object.

Parameters:
    data (np.ndarray): Array to plot a histogram of.
    plot_details_dict (dict): Dictionary with keys such as 'title', 'xlabel', etc.

Returns:
    Nothing. Mutates :self._pdf: with the new plot.

Definition at line 89 of file PDFPlotter.py.

92 plot_details_dict: dict) -> None:
93 """
94 Plot a histogram onto the PdfPages object.
95
96 Parameters:
97 data (np.ndarray): Array to plot a histogram of.
98 plot_details_dict (dict): Dictionary with keys such as 'title', 'xlabel', etc.
99
100 Returns:
101 Nothing. Mutates :self._pdf: with the new plot.
102 """
103 self._check_title_and_labels(plot_details_dict)
104
105 plt.figure(figsize=plot_details_dict.get('figsize', self._DEFAULT_FIG_SIZE))
106 ax = plt.gca()
107
108 # Custom xticks are for specific typing. Expect to see much
109 # smaller plots, so only do linear and use less bins.
110 if 'xticks' in plot_details_dict:
111 plt.xticks(**plot_details_dict['xticks'])
112
113 hist_style = plot_details_dict.get('hist_style', self._DEFAULT_HIST_STYLE)
114 bins = plot_details_dict.get('bins', self._DEFAULT_HIST_STYLE['bins'])
115
116 if plot_details_dict.get('linear', True) and plot_details_dict.get('log', True):
117 ax.hist(data, bins=bins, **plot_details_dict.get('linear_style', self._DEFAULT_HIST_STYLE['linear_style']))
118 ax.set_yscale('linear')
119
120 ax2 = ax.twinx()
121 ax2.hist(data, bins=bins, **plot_details_dict.get('log_style', self._DEFAULT_HIST_STYLE['log_style']))
122 ax2.set_yscale('log')
123
124 # Setting the plot order
125 ax.set_zorder(2)
126 ax.patch.set_visible(False)
127 ax2.set_zorder(1)
128
129 linear_color = plot_details_dict.get('linear_style', self._DEFAULT_HIST_STYLE).get('color', self._DEFAULT_HIST_STYLE['linear_style']['color'])
130 # Set axis and tick colors.
131 ax.spines['left'].set_color(linear_color)
132 ax.yaxis.label.set_color(linear_color)
133 ax.tick_params('y', colors=linear_color)
134
135 log_color = plot_details_dict.get('log_style', self._DEFAULT_HIST_STYLE).get('color', self._DEFAULT_HIST_STYLE['log_style']['color'])
136 ax.spines['right'].set_color(log_color) # Actually belongs to ax and not ax2.
137 ax2.yaxis.label.set_color(log_color)
138 ax2.tick_params('y', which='both', colors=log_color)
139
140 handles, labels = ax.get_legend_handles_labels()
141 handles2, labels2 = ax2.get_legend_handles_labels()
142 handles = handles + handles2
143 labels = labels + labels2
144 plt.legend(handles=handles, labels=labels)
145 else:
146 hist_style = plot_details_dict.get('linear_style', self._DEFAULT_HIST_STYLE['linear_style'])
147 if plot_details_dict.get('log', self._DEFAULT_HIST_STYLE['log']):
148 hist_style = plot_details_dict.get('log_style', self._DEFAULT_HIST_STYLE['log_style'])
149 plt.hist(data, bins=bins, **hist_style)
150 if plot_details_dict.get('log', False): # Default to linear, so only change on log
151 plt.yscale('log')
152
153 plt.title(plot_details_dict['title'])
154 ax.set_xlabel(plot_details_dict['xlabel'])
155 if 'xlim' in plot_details_dict:
156 plt.xlim(plot_details_dict['xlim'])
157
158 if plot_details_dict.get('use_integer_xticks', False):
159 ax.xaxis.set_major_locator(MultipleLocator(base=1))
160
161 plt.tight_layout()
162 self._pdf.savefig()
163 plt.close()
164
165 return None
166

Member Data Documentation

◆ _DEFAULT_ERRORBAR_STYLE

trgtools.plot.PDFPlotter.PDFPlotter._DEFAULT_ERRORBAR_STYLE
staticprotected
Initial value:
= dict(
capsize=4,
color='k',
ecolor='r',
marker='.',
markersize=0.01
)

Definition at line 37 of file PDFPlotter.py.

◆ _DEFAULT_FIG_SIZE

tuple trgtools.plot.PDFPlotter.PDFPlotter._DEFAULT_FIG_SIZE = (6, 4)
staticprotected

Definition at line 27 of file PDFPlotter.py.

◆ _DEFAULT_HIST_STYLE

trgtools.plot.PDFPlotter.PDFPlotter._DEFAULT_HIST_STYLE
staticprotected
Initial value:
= dict(
linear=True,
linear_style=dict(color='#63ACBE', alpha=0.6, label='Linear'),
log=True,
log_style=dict(color='#EE442F', alpha=0.6, label='Log'),
bins=100
)

Definition at line 29 of file PDFPlotter.py.

◆ _pdf

trgtools.plot.PDFPlotter.PDFPlotter._pdf = PdfPages(save_name)
protected

Definition at line 56 of file PDFPlotter.py.


The documentation for this class was generated from the following file: