mlchart.html


001| """mlChart - Mathplotlab Chart Framework.
001| 
001| Classes:
001|     mlchart             - abstract chart base class
001|     mlmonthchart        - abstract monthly chart base class
001|     mlunitsquarechart   - abstract square chart base class - -2 to +2 on both axes
001|     mltwocyclechart     - abstract square chart base class - 2 pi X axis
001| 
001| """

002| ####################################################################################################
003| from os import path
004| from math import pi, tau
005| from datetime import date
006| import matplotlib.pyplot as plt
007| from matplotlib.ticker import MultipleLocator, FormatStrFormatter
008| from matplotlib.dates import DateFormatter, MonthLocator
009| #from mpl_toolkits.mplot3d import axes3d
010| from goodies import KWARG, divisions
011| ####################################################################################################
012| 
013| 
014| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
015| class mlchart (object):
016|     '''MatPlotLib Chart Class.
016| 
016| Framework for basic Matplotlib charts.
016| 
016| Methods:
016|    .plotter             - sub-classes MUST override this!!
016|    .make                - create the chart
016|    .close               - close the figure, reset object refs to None
016|    .make_x_axis         - called by make() to set X-axis parameters
016|    .make_x_date_axis    - called by make() to set X-axis date parameters
016|    .make_y_axis         - called by make() to set Y-axis parameters
016|    .make_grid           - called by make() to set grid parameters
016|    .make_x_axis_rotate  - called by make() to rotate X-axis labels 90 degrees
016|    .make_x_axis_spcl    - override to tweak X-axis parameters
016|    .make_y_axis_spcl    - override to tweak Y-axis parameters
016| 
016| New instance keyword parameters (all have defaults):
016|         fname   ('chart.png')   - chart filename
016|         fpath   ('ZCZC')        - chart filepath
016|         title   ('My Chart')    - chart title
016|         xname   ('X Axis')      - X-axis title
016|         yname   ('Y Axis')      - Y-axis title
016|         xmin    (-10.0)         - X minumum
016|         xmax    (+10.0)         - X maximum
016|         ymin    (-1.0)          - Y minumum
016|         ymax    (+1.0)          - Y maximum
016|         xgrid1  (10.0)          - X-axis major tick marks
016|         xgrid2  (1.0)           - X-axis minor tick marks
016|         ygrid1  (1.0)           - Y-axis major tick marks
016|         ygrid2  ( 0.1)          - Y-axis minor tick marks
016|         xtickf  ('%+.2f')       - X-axis labels format
016|         ytickf  ('%+.2f')       - Y-axis labels format
016|         xrot    (0)             - rotate X-axis labels 90 degrees
016|         xdate   (0)             - set X-axis to use dates
016|         ml      (0.10)          - figure margin left
016|         mr      (0.97)          - figure margin right
016|         mb      (0.11)          - figure margin bottom
016|         mt      (0.91)          - figure margin top
016| '''

017|     def __init__ (self, dims=(8.0, 5.0), **kwargs):
018|         '''New mlchart instance. Requires dimensions. Other params allowed.'''
019|         # Size...
020|         self.dims = dims
021|         # Chart Filename...
022|         self.fname = KWARG('fname', 'chart.png', str, kwargs)
023|         self.fpath = KWARG('fpath', 'ZCZC', str, kwargs)
024|         # Labels...
025|         self.title = KWARG('title', 'My Chart', str, kwargs)
026|         self.title_kw = dict(fontweight='bold')
027|         self.x_title = KWARG('xname', 'X Axis', str, kwargs)
028|         self.x_title_kw = dict(fontweight='bold')
029|         self.y_title = KWARG('yname', 'Y Axis', str, kwargs)
030|         self.y_title_kw = dict(fontweight='bold')
031|         # Limits...
032|         xmin = KWARG('xmin', -10.0, float, kwargs)
033|         xmax = KWARG('xmax', +10.0, float, kwargs)
034|         ymin = KWARG('ymin',  -1.0, float, kwargs)
035|         ymax = KWARG('ymax',  +1.0, float, kwargs)
036|         self.x_limit = (xmin, xmax)
037|         self.y_limit = (ymin, ymax)
038|         # Grid...
039|         xgrid1 = KWARG('xgrid1', 10.0, float, kwargs)
040|         xgrid2 = KWARG('xgrid2',  1.0, float, kwargs)
041|         ygrid1 = KWARG('ygrid1',  1.0, float, kwargs)
042|         ygrid2 = KWARG('ygrid2',  0.1, float, kwargs)
043|         self.x_grids = (xgrid1, xgrid2)
044|         self.y_grids = (ygrid1, ygrid2)
045|         # Details...
046|         self.x_tickf = KWARG('xtickf', '%+.2f', str, kwargs)
047|         self.y_tickf = KWARG('ytickf', '%+.2f', str, kwargs)
048|         self.x_tickr = KWARG('xrot' , 0, int, kwargs)
049|         self.x_dates = KWARG('xdate', 0, int, kwargs)
050|         # Margins...
051|         ml = KWARG('ml', 0.10, float, kwargs)
052|         mr = KWARG('mr', 0.97, float, kwargs)
053|         mb = KWARG('mb', 0.11, float, kwargs)
054|         mt = KWARG('mt', 0.91, float, kwargs)
055|         self.margins = dict(left=ml, right=mr, bottom=mb, top=mt)
056|         self.fig = None
057|         self.ax = None
058| 
059|     def plotter (self):
060|         '''Sub-classes need to override this!'''
061|         ...
062| 
063|     def close (self):
064|         '''Close figure and set object references to None.'''
065|         plt.close(self.fig)
066|         self.fig = None
067|         self.ax = None
068| 
069|     def make (self, save=True, show=False, stream=None):
070|         '''Create the Chart.'''
071|         self.fig,self.ax = plt.subplots()
072|         # Chart title...
073|         if self.title:
074|             self.fig.suptitle(self.title, **self.title_kw)
075|         # Make the Axes and Grid...
076|         if self.x_dates:
077|             self.make_x_date_axis()
078|         else:
079|             self.make_x_axis()
080|         self.make_y_axis()
081|         self.make_grid()
082|         # Plot data...
083|         self.plotter()
084|         # Configure output...
085|         self.fig.set_figwidth(self.dims[0])
086|         self.fig.set_figheight(self.dims[1])
087|         self.fig.subplots_adjust(**self.margins)
088|         # Save the chart (maybe; usually)...
089|         if save:
090|             fn = path.join(self.fpath, self.fname)
091|             self.fig.savefig(fn)
092|         if stream:
093|             self.fig.savefig(stream, format='png')
094|         # Display the chart (maybe; usually not)...
095|         if show:
096|             plt.show()
097| 
098|     def make_x_axis (self):
099|         '''Configure the X-Axis.'''
100|         # Axis title...
101|         if self.x_title:
102|             self.ax.set_xlabel(self.x_title, **self.x_title_kw)
103|         # Axis limits...
104|         self.ax.set_xlim(self.x_limit[0], self.x_limit[1])
105|         # Axis tick marks...
106|         if self.x_grids[0]:
107|             self.ax.xaxis.set_major_locator(MultipleLocator(self.x_grids[0]))
108|         if self.x_grids[1]:
109|             self.ax.xaxis.set_minor_locator(MultipleLocator(self.x_grids[1]))
110|         # Axis tick labels...
111|         if self.x_tickf:
112|             self.ax.xaxis.set_major_formatter(FormatStrFormatter(self.x_tickf))
113|         if self.x_tickr:
114|             self.make_x_axis_rotate()
115|         # Axis special processing...
116|         self.make_x_axis_spcl()
117| 
118|     def make_x_date_axis (self):
119|         '''Configure the X-Axis for dates.'''
120|         self.ax.xaxis_date()
121|         # Axis title...
122|         if self.x_title:
123|             self.ax.set_xlabel(self.x_title, **self.x_title_kw)
124|         # Axis limits...
125|         self.ax.set_xlim(self.x_limit[0], self.x_limit[1])
126|         # Axis tick marks...
127|         if self.x_grids[0]:
128|             self.ax.xaxis.set_major_locator(MonthLocator(self.x_grids[0]))
129|         if self.x_grids[1]:
130|             self.ax.xaxis.set_minor_locator(MonthLocator(self.x_grids[1]))
131|         # Axis tick labels...
132|         if self.x_tickf:
133|             self.ax.xaxis.set_major_formatter(DateFormatter(self.x_tickf))
134|         if self.x_tickr:
135|             self.make_x_axis_rotate()
136| 
137|     def make_y_axis (self):
138|         '''Configure the Y-Axis.'''
139|         # Axis title...
140|         if self.y_title:
141|             self.ax.set_ylabel(self.y_title, **self.y_title_kw)
142|         # Axis limits...
143|         self.ax.set_ylim(self.y_limit[0], self.y_limit[1])
144|         # Axis tick marks...
145|         if self.y_grids[0]:
146|             self.ax.yaxis.set_major_locator(MultipleLocator(self.y_grids[0]))
147|         if self.y_grids[1]:
148|             self.ax.yaxis.set_minor_locator(MultipleLocator(self.y_grids[1]))
149|         # Axis tick labels...
150|         if self.y_tickf:
151|             self.ax.yaxis.set_major_formatter(FormatStrFormatter(self.y_tickf))
152|         # Axis special processing...
153|         self.make_y_axis_spcl()
154| 
155|     def make_grid (self):
156|         '''Configure the Grid.'''
157|         self.ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
158|         self.ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
159|         self.ax.tick_params(which='major', axis='both', direction='out', color='#000000')
160|         self.ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
161| 
162|     def make_x_axis_rotate (self):
163|         '''Rotate X-Axis labels.'''
164|         for tick in self.ax.xaxis.get_major_ticks():
165|             tick.label1.set_rotation('vertical')
166|             tick.label1.set_size(9)
167| 
168|     def make_x_axis_spcl (self):
169|         '''Wedge for sub-class to set X-axis parameters.'''
170|         ...
171| 
172|     def make_y_axis_spcl (self):
173|         '''Wedge for sub-class to set Y-axis parameters.'''
174|         ...
175| 
176| 
177| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
178| class mlmonthchart (mlchart):
179|     '''Sub-class of mlchart for making charts with months as the X-axis.'''
180| 
181|     def __init__ (self, dims=(12.0, 4.0), **kwargs):
182|         '''New mlmonthchart instance.'''
183|         super().__init__(dims, **kwargs)
184|         self.title = 'Stuff per Month'
185|         self.x_dates = True
186|         self.x_limit = (date(2010,1,1),date(2020,1,1))
187|         self.x_grids = (1, [4,7,10])
188|         self.x_tickf = '%Y'
189|         self.x_tickr = True
190|         self.x_title = 'Year'
191|         self.y_limit = (0, 100)
192|         self.y_grids = (25, 5)
193|         self.y_tickf = '%d'
194|         self.y_title = 'Stuff'
195|         self.margins['left'] = 0.06
196|         self.margins['right'] = 0.98
197|         self.margins['bottom'] = 0.17
198| 
199|     def plotter (self):
200|         '''Don't forget to override this!'''
201|         ...
202| 
203| 
204| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
205| class mlunitsquarechart (mlchart):
206|     '''Sub-class of mlchart for making unit-square charts.'''
207| 
208|     def __init__ (self, dims=(5.0, 5.0), **kwargs):
209|         '''New mlunitsquarechart instance.'''
210|         super().__init__(dims, **kwargs)
211|         self.x_limit = (-2.0, +2.0)
212|         self.y_limit = (-2.0, +2.0)
213|         self.x_grids = (1.0, 0.1)
214|         self.y_grids = (1.0, 0.1)
215|         self.margins['left'] = 0.16
216|         self.margins['right'] = 0.95
217|         self.margins['bottom'] = 0.11
218|         self.margins['top'] = 0.91
219| 
220|     def plotter (self):
221|         '''Don't forget to override this!'''
222|         ...
223| 
224| 
225| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
226| class mltwocyclechart (mlchart):
227|     '''Sub-class of mlchart for making charts with -tau to +tau X-axis.'''
228| 
229|     def __init__ (self, dims=(8.0, 4.0), **kwargs):
230|         '''New mltwocyclechart instance.'''
231|         super().__init__(dims, **kwargs)
232|         self.x_limit = (-tau, +tau)
233|         self.y_limit = (-2.0, +2.0)
234|         self.x_grids = (pi, pi/4.0)
235|         self.y_grids = (1.0, 0.1)
236|         self.xticks = [-tau, -pi, 0, +pi, +tau]
237|         self.xs = divisions(-tau, +tau, 1000)
238|         self.margins['bottom'] = 0.12
239| 
240|     def plotter (self):
241|         '''Don't forget to override this!'''
242|         ...
243| 
244|     def make_x_axis_spcl (self):
245|         self.ax.set_xticks(self.xticks)
246|         self.ax.set_xticklabels(['%+d $pi$' % int(x/pi) for x in self.xticks])
247| 
248| 
249| 
250| ####################################################################################################
251| '''eof'''
252|