xdenisx

windrose

Nov 11th, 2014
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.57 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. #
  3. #
  4. # windrose.py
  5. #
  6. # purpose:  Create a windrose plot.
  7. # author:   Filipe P. A. Fernandes
  8. # e-mail:   ocefpaf@gmail
  9. # web:      http://ocefpaf.tiddlyspot.com/
  10. # created:  26-Jun-2012
  11. # modified: Tue 26 Jun 2012 04:54:03 PM BRT by Denis Demchev
  12. #
  13. # obs:
  14. #
  15.  
  16. import numpy as np
  17. import matplotlib.cm as cm
  18. import matplotlib.pyplot as plt
  19. import sys
  20.  
  21. from matplotlib.patches import Rectangle
  22. from matplotlib.pylab import poly_between
  23. from numpy.lib.twodim_base import histogram2d
  24. from matplotlib.projections.polar import PolarAxes
  25.  
  26.  
  27. # The starting zorder for all drawing, negative to have the grid on
  28. ZBASE, RESOLUTION = -1000, 100
  29.  
  30.  
  31. class WindroseAxes(PolarAxes):
  32.     """Create a wind-rose axes."""
  33.  
  34.     def __init__(self, *args, **kwargs):
  35.         r"""See Axes base class for args and kwargs documentation."""
  36.  
  37.         # Uncomment to have the possibility to change the resolution directly
  38.         # when the instance is created:
  39.         #self.RESOLUTION = kwargs.pop('resolution', 100)
  40.         PolarAxes.__init__(self, *args, **kwargs)
  41.         self.set_aspect('equal', adjustable='box', anchor='C')
  42.         self.radii_angle = 67.5
  43.         self.cla()
  44.  
  45.     def cla(self):
  46.         """Clear the current axes."""
  47.         PolarAxes.cla(self)
  48.  
  49.         self.theta_angles = np.arange(0, 360, 45)
  50.         self.theta_labels = ['E', 'N-E', 'N', 'N-W', 'W', 'S-W', 'S', 'S-E']
  51.         if 0:
  52.             self.theta_labels = [u'90\u00B0', u'45\u00B0', u'0\u00B0',
  53.                                  u'315\u00B0', u'270\u00B0', u'225\u00B0',
  54.                                  u'180\u00B0', u'135\u00B0']
  55.         self.set_thetagrids(angles=self.theta_angles, labels=self.theta_labels)
  56.  
  57.         self._info = {'dir': list(),
  58.                       'bins': list(),
  59.                       'table': list()}
  60.  
  61.         self.patches_list = list()
  62.  
  63.     def _colors(self, cmap, n):
  64.         r"""Returns a list of n colors based on the colormap cmap."""
  65.         return [cmap(i) for i in np.linspace(0.0, 1.0, n)]
  66.  
  67.     def set_radii_angle(self, **kwargs):
  68.         """Set the radii labels angle."""
  69.  
  70.         kwargs.pop('labels', None)
  71.         angle = kwargs.pop('angle', None)
  72.         if angle is None:
  73.             angle = self.radii_angle
  74.         self.radii_angle = angle
  75.         radii = np.linspace(0.1, self.get_rmax(), 6)
  76.         radii_labels = ["%.1f" % r for r in radii]
  77.         radii_labels[0] = ""  # Removing label 0
  78.         self.set_rgrids(radii=radii, labels=radii_labels,
  79.                         angle=self.radii_angle, **kwargs)
  80.  
  81.     def _update(self):
  82.         self.set_rmax(rmax=np.max(np.sum(self._info['table'], axis=0)))
  83.         self.set_radii_angle(angle=self.radii_angle)
  84.  
  85.     def legend(self, loc='lower left', **kwargs):
  86.         r"""
  87.        Sets the legend location and her properties.
  88.        The location codes are
  89.  
  90.          'best'         : 0,
  91.          'upper right'  : 1,
  92.          'upper left'   : 2,
  93.          'lower left'   : 3,
  94.          'lower right'  : 4,
  95.          'right'        : 5,
  96.          'center left'  : 6,
  97.          'center right' : 7,
  98.          'lower center' : 8,
  99.          'upper center' : 9,
  100.          'center'       : 10,
  101.  
  102.        If none of these are suitable, loc can be a 2-tuple giving x,y
  103.        in axes coords, ie,
  104.  
  105.          loc = (0, 1) is left top
  106.          loc = (0.5, 0.5) is center, center
  107.  
  108.        and so on.  The following kwargs are supported:
  109.  
  110.        isaxes = True        # whether this is an axes legend
  111.        pad = 0.2            # fractional white space inside the legend border
  112.        shadow               # if True, draw a shadow behind legend
  113.        labelsep = 0.005     # vertical space between the legend entries
  114.        handlelen = 0.05     # length of the legend lines
  115.        handletextsep = 0.02 # space between the legend line and legend text
  116.        axespad = 0.02       # border between the axes and legend edge
  117.        prop = FontProperties(size='smaller')  # the font property
  118.        """
  119.  
  120.         def get_handles():
  121.             handles = list()
  122.             for p in self.patches_list:
  123.                 if isinstance(p, matplotlib.patches.Polygon) or \
  124.                 isinstance(p, matplotlib.patches.Rectangle):
  125.                     color = p.get_facecolor()
  126.                 elif isinstance(p, matplotlib.lines.Line2D):
  127.                     color = p.get_color()
  128.                 else:
  129.                     raise AttributeError("Can't handle patches")
  130.                 handles.append(Rectangle((0, 0), 0.2, 0.2,
  131.                     facecolor=color, edgecolor='black'))
  132.             return handles
  133.  
  134.         def get_labels():
  135.             labels = np.copy(self._info['bins'])
  136.             labels = ["[%.1f : %0.1f]" % (labels[i], labels[i + 1])
  137.                       for i in range(len(labels) - 1)]
  138.  
  139.             # Hack to replace inf and 0 for > and <.
  140.             labels[-1] = labels[-1].replace(' : inf', '').replace('[', '[>')
  141.             labels[0] = labels[0].replace('[0.0 : ', '[<')
  142.             return labels
  143.  
  144.         kwargs.pop('labels', None)
  145.         kwargs.pop('handles', None)
  146.         handles = get_handles()
  147.         labels = get_labels()
  148.         self.legend_ = matplotlib.legend.Legend(self, handles, labels, loc,
  149.                                                                      **kwargs)
  150.         return self.legend_
  151.  
  152.     def _init_plot(self, dir, var, **kwargs):
  153.         r"""Internal method used by all plotting commands."""
  154.         kwargs.pop('zorder', None)
  155.  
  156.         # Initialization of the bins array if not set.
  157.         bins = kwargs.pop('bins', None)
  158.         if bins is None:
  159.             bins = np.linspace(np.min(var), np.max(var), 6)
  160.         if isinstance(bins, int):
  161.             bins = np.linspace(np.min(var), np.max(var), bins)
  162.         bins = np.asarray(bins)
  163.         nbins = len(bins)
  164.  
  165.         # Number of sectors.
  166.         nsector = kwargs.pop('nsector', None)
  167.         if nsector is None:
  168.             nsector = 8
  169.  
  170.         # Sets the colors table based on the colormap or the "colors" argument.
  171.         colors = kwargs.pop('colors', None)
  172.         cmap = kwargs.pop('cmap', None)
  173.         if colors is not None:
  174.             if isinstance(colors, str):
  175.                 colors = [colors] * nbins
  176.             if isinstance(colors, (tuple, list)):
  177.                 if len(colors) != nbins:
  178.                     raise ValueError("colors and bins must have same length")
  179.         else:
  180.             if cmap is None:
  181.                 cmap = cm.jet
  182.             colors = self._colors(cmap, nbins)
  183.  
  184.         # Building the angles list
  185.         angles = np.arange(0, -2 * np.pi, -2 * np.pi / nsector) + np.pi / 2
  186.  
  187.         normed = kwargs.pop('normed', False)
  188.         blowto = kwargs.pop('blowto', False)
  189.  
  190.         # Set the global information dictionary.
  191.        
  192.         self._info['dir'], self._info['bins'], self._info['table'], \
  193.         self._info['table_numbers']= \
  194.                            histogram(dir, var, bins, nsector, normed, blowto)
  195.  
  196.         return bins, nbins, nsector, colors, angles, kwargs
  197.  
  198.     def contour(self, dir, var, **kwargs):
  199.         r"""
  200.        Plot a wind-rose in linear mode. For each var bins, a line will be
  201.        draw on the axes, a segment between each sector (center to center).
  202.        Each line can be formatted (color, width, ...) like with standard plot
  203.        pylab command.
  204.  
  205.        Mandatory:
  206.        * dir : 1D array - directions the wind blows from, North centered
  207.        * var : 1D array - values of the variable to compute. Typically the
  208.        wind speeds
  209.        Optional:
  210.        * nsector: integer - number of sectors used to compute the wind-rose
  211.        table. If not set, nsectors=8, then each sector will be 360/8=45°,
  212.        and the resulting computed table will be aligned with the cardinals
  213.        points.
  214.        * bins : 1D array or integer- number of bins, or a sequence of
  215.        bins variable. If not set, bins=6, then
  216.            bins=linspace(min(var), max(var), 6)
  217.        * blowto : bool. If True, the wind-rose will be pi rotated,
  218.        to show where the wind blow to (useful for pollutant rose).
  219.        * colors : string or tuple - one string color ('k' or 'black'), in
  220.        this case all bins will be plotted in this color; a tuple of matplotlib
  221.        color args (string, float, rgb, etc), different levels will be plotted
  222.        in different colors in the order specified.
  223.        * cmap : a cm Colormap instance from matplotlib.cm.
  224.          - if cmap == None and colors == None, a default Colormap is used.
  225.  
  226.        others kwargs : see help(pylab.plot)
  227.        """
  228.  
  229.         bins, nbins, nsector, colors, angles, kwargs = self._init_plot(dir,
  230.                                                                 var, **kwargs)
  231.  
  232.         # Closing lines.
  233.         angles = np.hstack((angles, angles[-1] - 2 * np.pi / nsector))
  234.         vals = np.hstack((self._info['table'],
  235.                          np.reshape(self._info['table'][:, 0],
  236.                                    (self._info['table'].shape[0], 1))))
  237.  
  238.         offset = 0
  239.         for i in range(nbins):
  240.             val = vals[i, :] + offset
  241.             offset += vals[i, :]
  242.             zorder = ZBASE + nbins - i
  243.             patch = self.plot(angles, val, color=colors[i], zorder=zorder,
  244.                               **kwargs)
  245.             self.patches_list.extend(patch)
  246.         self._update()
  247.  
  248.     def contourf(self, dir, var, **kwargs):
  249.         r"""
  250.        Plot a wind-rose in filled mode. For each var bins, a line will be
  251.        draw on the axes, a segment between each sector (center to center).
  252.        Each line can be formatted (color, width, ...) like with standard plot
  253.        pylab command.
  254.  
  255.        Mandatory:
  256.        * dir : 1D array - directions the wind blows from, North centered
  257.        * var : 1D array - values of the variable to compute. Typically the
  258.        wind speeds
  259.        Optional:
  260.        * nsector: integer - number of sectors used to compute the wind-rose
  261.        table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
  262.        and the resulting computed table will be aligned with the cardinals
  263.        points.
  264.        * bins : 1D array or integer- number of bins, or a sequence of
  265.        bins variable. If not set, bins=6, then
  266.            bins=linspace(min(var), max(var), 6)
  267.        * blowto : bool. If True, the wind-rose will be pi rotated,
  268.        to show where the wind blow to (useful for pollutant rose).
  269.        * colors : string or tuple - one string color ('k' or 'black'), in this
  270.        case all bins will be plotted in this color; a tuple of matplotlib
  271.        color args (string, float, rgb, etc), different levels will be plotted
  272.        in different colors in the order specified.
  273.        * cmap : a cm Colormap instance from matplotlib.cm.
  274.          - if cmap == None and colors == None, a default Colormap is used.
  275.  
  276.        others kwargs : see help(pylab.plot)
  277.        """
  278.  
  279.         bins, nbins, nsector, colors, angles, kwargs = self._init_plot(dir,
  280.                                                                 var, **kwargs)
  281.         kwargs.pop('facecolor', None)
  282.         kwargs.pop('edgecolor', None)
  283.  
  284.         #closing lines
  285.         angles = np.hstack((angles, angles[-1] - 2 * np.pi / nsector))
  286.         vals = np.hstack((self._info['table'],
  287.                          np.reshape(self._info['table'][:, 0],
  288.                                    (self._info['table'].shape[0], 1))))
  289.         offset = 0
  290.         for i in range(nbins):
  291.             val = vals[i, :] + offset
  292.             offset += vals[i, :]
  293.             zorder = ZBASE + nbins - i
  294.             xs, ys = poly_between(angles, 0, val)
  295.             patch = self.fill(xs, ys, facecolor=colors[i],
  296.                               edgecolor=colors[i], zorder=zorder, **kwargs)
  297.             self.patches_list.extend(patch)
  298.  
  299.     def bar(self, dir, var, **kwargs):
  300.         r"""
  301.        Plot a wind-rose in bar mode. For each var bins and for each sector,
  302.        a colored bar will be draw on the axes.
  303.  
  304.        Mandatory:
  305.        * dir : 1D array - directions the wind blows from, North centered
  306.        * var : 1D array - values of the variable to compute. Typically the
  307.        wind speeds
  308.        Optional:
  309.        * nsector: integer - number of sectors used to compute the wind-rose
  310.        table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
  311.        and the resulting computed table will be aligned with the cardinals
  312.        points.
  313.        * bins : 1D array or integer- number of bins, or a sequence of
  314.        bins variable. If not set, bins=6 between min(var) and max(var).
  315.        * blowto : bool. If True, the wind-rose will be pi rotated,
  316.        to show where the wind blow to (useful for pollutant rose).
  317.        * colors : string or tuple - one string color ('k' or 'black'), in this
  318.        case all bins will be plotted in this color; a tuple of matplotlib
  319.        color args (string, float, rgb, etc), different levels will be plotted
  320.        in different colors in the order specified.
  321.        * cmap : a cm Colormap instance from matplotlib.cm.
  322.          - if cmap == None and colors == None, a default Colormap is used.
  323.        edgecolor : string - The string color each edge bar will be plotted.
  324.        Default : no edgecolor
  325.        * opening : float - between 0.0 and 1.0, to control the space between
  326.        each sector (1.0 for no space)
  327.        """
  328.  
  329.         bins, nbins, nsector, colors, angles, kwargs = self._init_plot(dir,
  330.                                                                 var, **kwargs)
  331.         kwargs.pop('facecolor', None)
  332.         edgecolor = kwargs.pop('edgecolor', None)
  333.         if edgecolor is not None:
  334.             if not isinstance(edgecolor, str):
  335.                 raise ValueError('edgecolor must be a string color')
  336.         opening = kwargs.pop('opening', None)
  337.         if opening is None:
  338.             opening = 0.8
  339.         dtheta = 2 * np.pi / nsector
  340.         opening = dtheta * opening
  341.  
  342.         for j in range(nsector):
  343.             offset = 0
  344.             for i in range(nbins):
  345.                 if i > 0:
  346.                     offset += self._info['table'][i - 1, j]
  347.                 val = self._info['table'][i, j]
  348.                 zorder = ZBASE + nbins - i
  349.                 patch = Rectangle((angles[j] - opening / 2, offset), opening,
  350.                                   val, facecolor=colors[i],
  351.                                   edgecolor=edgecolor, zorder=zorder,
  352.                                   **kwargs)
  353.                 self.add_patch(patch)
  354.                 if j == 0:
  355.                     self.patches_list.append(patch)
  356.         self._update()
  357.  
  358.  
  359.     def box(self, dir, var, **kwargs):
  360.         r"""
  361.        Plot a wind-rose in proportional bar mode. For each var bins and for
  362.        each sector, a colored bar will be draw on the axes.
  363.  
  364.        Mandatory:
  365.        * dir : 1D array - directions the wind blows from, North centered
  366.        * var : 1D array - values of the variable to compute. Typically the
  367.        wind speeds
  368.        Optional:
  369.        * nsector: integer - number of sectors used to compute the wind-rose
  370.        table. If not set, nsectors=16, then each sector will be 360/16=22.5°,
  371.        and the resulting computed table will be aligned with the cardinals
  372.        points.
  373.        * bins : 1D array or integer- number of bins, or a sequence of
  374.        bins variable. If not set, bins=6 between min(var) and max(var).
  375.        * blowto : bool. If True, the wind-rose will be pi rotated,
  376.        to show where the wind blow to (useful for pollutant rose).
  377.        * colors : string or tuple - one string color ('k' or 'black'), in this
  378.        case all bins will be plotted in this color; a tuple of matplotlib
  379.        color args (string, float, rgb, etc), different levels will be plotted
  380.        in different colors in the order specified.
  381.        * cmap : a cm Colormap instance from matplotlib.cm.
  382.          - if cmap == None and colors == None, a default Colormap is used.
  383.        edgecolor : string - The string color each edge bar will be plotted.
  384.        Default : no edgecolor
  385.        """
  386.         statistics = []
  387.         bins, nbins, nsector, colors, angles, kwargs = self._init_plot(dir,
  388.                                                                 var, **kwargs)
  389.         kwargs.pop('facecolor', None)
  390.         edgecolor = kwargs.pop('edgecolor', None)
  391.         if edgecolor is not None:
  392.             if not isinstance(edgecolor, str):
  393.                 raise ValueError('edgecolor must be a string color')
  394.         opening = np.linspace(0.0, np.pi / 16, nbins)
  395.  
  396.         ##############################
  397.         # Bar plotting
  398.         ##############################
  399.         def plot_hist(bins,speed_number):
  400.  
  401.             f = plt.figure()
  402.             ax = f.add_axes([0.1, 0.1, 0.8, 0.8])
  403.             plt.ylim(0, max(speed_number)+5)
  404.             bins = np.append(bins,[1.5])
  405.             print bins
  406.             print speed_number
  407.             ax.bar(bins, speed_number, color='#81A594', edgecolor='#00628B', \
  408.                 align='center')
  409.  
  410.             #for x,y in zip(weeks_barb, targets_barb):
  411.             #    text(x, y+1, '%.0f' % y, ha='center', va= 'bottom')
  412.  
  413.             ax.set_xticks(bins)
  414.             ax.set_xticklabels(bins)
  415.             plt.ylabel('Ice Target Distribution by Speed')
  416.             plt.xlabel('Speed')
  417.             f.savefig('pics\\vessel_targets_hist.png', dpi=200, bbox_inches='tight')
  418.             plt.clf()
  419.  
  420.         ##############################
  421.         # Save data to a csv file
  422.         ##############################
  423.      
  424.         def data_to_file(iname):
  425.             istr = ','
  426.             targets = []
  427.             for ii in range(len(self._info['dir'])):
  428.                 try:
  429.                     istr = istr + ('%s-%s,' % (self._info['dir'][ii], self._info['dir'][ii+1]))
  430.                 except:
  431.                     istr = istr + ('%s-%s,' % (self._info['dir'][ii-1], self._info['dir'][0]))
  432.                     test_ff.write(istr+'Total\n')
  433.                
  434.        
  435.             for ii in range(len(self._info['bins'])):
  436.                 try:
  437.                     if str(self._info['bins'][ii+1])<> 'inf':
  438.                         istr = ('%s-%s' % (self._info['bins'][ii], self._info['bins'][ii+1]))
  439.                         for jj in range(len(self._info[iname][0][:])):
  440.                             istr = istr + ',' + str(self._info[iname][ii][jj])
  441.                         #print istr
  442.                         isum = np.sum(self._info[iname][ii][:])
  443.                         #print isum
  444.                         istr = '%s,%s' % (istr, str(isum))
  445.                         test_ff.write('%s\n' % istr)
  446.                        
  447.                 except:
  448.                     istr = ('>%s' % (self._info['bins'][ii-1]))
  449.                     for jj in range(len(self._info[iname][0][:])):
  450.                         istr = istr + ',' + str(self._info[iname][ii-1][jj])
  451.                     #print istr
  452.                     isum = np.sum(self._info[iname][ii-1][:])
  453.                     istr = '%s,%s' % (istr, str(isum))
  454.                     targets.append(isum)
  455.                     test_ff.write('%s\n' % istr)
  456.                
  457.             # Last line with total numbers
  458.             print self._info[iname]
  459.             istr= ','
  460.             total_sum = np.sum(self._info[iname])
  461.             for jj in range(len(self._info[iname][0,:])):
  462.                 try:
  463.                     vert_sum = np.sum(self._info[iname][:,jj])
  464.                 except:
  465.                     pass
  466.                 istr = istr + ('%s,' % str(vert_sum))
  467.             test_ff.write('%s%s\n' % (istr, total_sum))
  468.             # Plot histograms
  469.             #targ = np.array(targets)
  470.         test_ff = open('txt\\vessels_dirs.csv','w')
  471.         data_to_file('table_numbers')
  472.         test_ff.write('\n\n')
  473.         data_to_file('table')
  474.         test_ff.close()
  475.  
  476.         for j in range(nsector):
  477.             offset = 0
  478.             for i in range(nbins):
  479.                 if i > 0:
  480.                     offset += self._info['table'][i - 1, j]
  481.                 val = self._info['table'][i, j]
  482.                
  483.                 zorder = ZBASE + nbins - i
  484.                 patch = Rectangle((angles[j] - opening[i] / 2, offset),
  485.                                   opening[i], val, facecolor=colors[i],
  486.                                   edgecolor=edgecolor, zorder=zorder, **kwargs)
  487.                 self.add_patch(patch)
  488.                 if j == 0:
  489.                     self.patches_list.append(patch)
  490.         self._update()
  491.        
  492. def histogram(dir, var, bins, nsector, normed=False, blowto=False):
  493.     r"""
  494.    Returns an array where, for each sector of wind
  495.    (centered on the north), we have the number of time the wind comes with a
  496.    particular var (speed, pollutant concentration, ...).
  497.    * dir : 1D array - directions the wind blows from, North centered
  498.    * var : 1D array - values of the variable to compute. Typically the wind
  499.    speeds
  500.    * bins : list - list of var category against we're going to compute the
  501.    table
  502.    * nsector : integer - number of sectors
  503.    * normed : boolean - The resulting table is normed in percent or not.
  504.    * blowto : boolean - Normally a wind-rose is computed with directions
  505.    as wind blows from. If true, the table will be reversed (useful for
  506.    pollutant-rose)
  507.    """
  508.  
  509.     if len(var) != len(dir):
  510.         raise ValueError("var and dir must have same length")
  511.  
  512.     angle = 360. / nsector
  513.  
  514.     dir_bins = np.arange(-angle / 2, 360. + angle, angle, dtype=np.float)
  515.     dir_edges = dir_bins.tolist()
  516.     dir_edges.pop(-1)
  517.     dir_edges[0] = dir_edges.pop(-1)
  518.     dir_bins[0] = 0.
  519.  
  520.     var_bins = bins.tolist()
  521.     var_bins.append(np.inf)
  522.  
  523.     if blowto:
  524.         dir = dir + 180.
  525.         dir[dir >= 360.] = dir[dir >= 360.] - 360
  526.  
  527.  
  528.     table = histogram2d(x=var, y=dir, bins=[var_bins, dir_bins],
  529.                           normed=False)[0]
  530.  
  531.     # Table with numbers
  532.     table_numbers = histogram2d(x=var, y=dir, bins=[var_bins, dir_bins],
  533.                           normed=False)[0]
  534.  
  535.     # Add the last value to the first to have the table of North winds,
  536.     table[:, 0] = table[:, 0] + table[:, -1]
  537.     table_numbers[:, 0] = table_numbers[:, 0] + table_numbers[:, -1]
  538.    
  539.     # and remove the last column.
  540.     table = table[:, :-1]
  541.     table_numbers = table_numbers[:, :-1]
  542.    
  543.     #print table_numbers
  544.     if normed:
  545.         table = table * 100 / table.sum()
  546.    
  547.     return dir_edges, var_bins, table, table_numbers
  548.  
  549.  
  550. def wrcontour(dir, var, **kwargs):
  551.     fig = plt.figure()
  552.     rect = [0.1, 0.1, 0.8, 0.8]
  553.     ax = WindroseAxes(fig, rect)
  554.     fig.add_axes(ax)
  555.     ax.contour(dir, var, **kwargs)
  556.     l = ax.legend(axespad=-0.10)
  557.     plt.setp(l.get_texts(), fontsize=8)
  558.     plt.draw()
  559.     plt.show()
  560.     return ax
  561.  
  562.  
  563. def wrcontourf(dir, var, **kwargs):
  564.     fig = plt.figure()
  565.     rect = [0.1, 0.1, 0.8, 0.8]
  566.     ax = WindroseAxes(fig, rect)
  567.     fig.add_axes(ax)
  568.     ax.contourf(dir, var, **kwargs)
  569.     l = ax.legend(axespad=-0.10)
  570.     plt.setp(l.get_texts(), fontsize=8)
  571.     plt.draw()
  572.     plt.show()
  573.     return ax
  574.  
  575.  
  576. def wrbox(dir, var, **kwargs):
  577.     fig = plt.figure()
  578.     rect = [0.1, 0.1, 0.8, 0.8]
  579.     ax = WindroseAxes(fig, rect)
  580.     fig.add_axes(ax)
  581.     ax.box(dir, var, **kwargs)
  582.     l = ax.legend(axespad=-0.10)
  583.     plt.setp(l.get_texts(), fontsize=8)
  584.     plt.draw()
  585.     plt.show()
  586.     return ax
  587.  
  588.  
  589. def wrbar(dir, var, **kwargs):
  590.     fig = plt.figure()
  591.     rect = [0.1, 0.1, 0.8, 0.8]
  592.     ax = WindroseAxes(fig, rect)
  593.     fig.add_axes(ax)
  594.     ax.bar(dir, var, **kwargs)
  595.     l = ax.legend(axespad=-0.10)
  596.     plt.setp(l.get_texts(), fontsize=8)
  597.     plt.draw()
  598.     plt.show()
  599.     return ax
  600.  
  601.  
  602. def clean(dir, var):
  603.     r"""Remove masked values in the two arrays, where if a direction data is
  604.    masked, the var data will also be removed in the cleaning process
  605.    (and vice-versa)."""
  606.  
  607.     if dir.mask:
  608.         dirmask = False
  609.     if var.mask:
  610.         varmask = False
  611.     ind = dirmask * varmask
  612.     return dir[ind], var[ind]
  613. if __name__ == '__main__':
  614.     import matplotlib
  615.     matplotlib.interactive(False)
  616.     plt.clf()
  617.     ff =sys.argv[1]
  618.     data = np.genfromtxt(ff, unpack=True)
  619.     vv = data[0]
  620.     vv_masked = np.ma.array(vv, mask = (vv>2.), copy=True)
  621.     dv = data[1]
  622.     dv_masked = np.ma.array(dv, mask = (dv == 999.), copy=True)
  623.  
  624.     # Statisctis on direction and speed
  625.     #probability(vv_masked, dv_masked)
  626.  
  627.     #vv = [5,15,2,31,1,15,7,2]#np.random.random(100) * 10
  628.     #dv = [100,90,213,130,180,53,230,21]#np.random.random(100) * 360
  629.     #vv_masked = np.ma.array(vv, mask = (vv == 999.), copy=True)
  630.     #dv_masked = np.ma.array(dv, mask = (dv == 999.), copy=True)
  631.     fig = plt.figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w')
  632.     rect = [0.1, 0.1, 0.8, 0.8]
  633.     ax = WindroseAxes(fig, rect, axisbg='w')
  634.     fig.add_axes(ax)
  635.    
  636.     vv = vv_masked.compressed()
  637.     dv = dv_masked.compressed()
  638.    
  639.     #ax.contourf(dv, vv, bins=np.arange(0,max(vv),0.25), cmap=cm.Set1)
  640.     #ax.contour(dv, vv, bins=np.arange(0,max(vv),0.25), colors='k')
  641.     ax.box(dv, vv, bins=[0.0,0.2,0.4,0.6,0.8,1.0,1.2] , normed=True)
  642.     #ax.bar(dv, vv, normed=True, opening=0.8, bins=8, edgecolor='white')
  643.  
  644.     l = ax.legend(axespad=-0.10)
  645.     #plt.setp(l.get_texts(), fontsize=8)
  646.    
  647.  
  648.     def new_axes():
  649.         fig = plt.figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w')
  650.         rect = [0.1, 0.1, 0.8, 0.8]
  651.         ax = WindroseAxes(fig, rect, axisbg='w')
  652.         fig.add_axes(ax)
  653.         return ax
  654.  
  655.     def set_legend(ax):
  656.         l = ax.legend(axespad=-0.10)
  657.         plt.setp(l.get_texts(), fontsize=8)
  658.  
  659.     ## Wind-rose like a stacked histogram with normed values (displayed in
  660.     ##percent).
  661.     #ax = new_axes()
  662.     #ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
  663.     #set_legend(ax)
  664.  
  665.     ## Another stacked histogram representation, not normed, with bins limits
  666.     #ax = new_axes()
  667.     #ax.box(wd, ws, bins=arange(0, 8, 1))
  668.     #set_legend(ax)
  669.  
  670.     ## A wind-rose in filled representation, with a controlled colormap
  671.     #ax = new_axes()
  672.     #ax.contourf(wd, ws, bins=arange(0, 8, 1), cmap=cm.hot)
  673.     #set_legend(ax)
  674.  
  675.     ## Same as above, but with contours over each filled region...
  676.     #ax = new_axes()
  677.     #ax.contourf(dv, vv, bins=np.arange(0, 1.4, 0.2))
  678.     #ax.contour(dv, vv, bins=np.arange(0, 1.5, 0.25), colors='black')
  679.     #set_legend(ax)
  680.  
  681.     ## ...or without filled regions
  682.     #ax = new_axes()
  683.     #ax.contour(dv, vv, bins=np.arange(0, 8, 1), cmap=cm.hot, lw=3)
  684.     #set_legend(ax)
  685.  
  686.     ##print ax._info
  687.     #plt.show()
  688.     plt.savefig('pics\\rose.png', dpi=200, bbox_inches='tight', pad_inches = 0.5)
Advertisement
Add Comment
Please, Sign In to add comment