def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) # data. This one is aware of rmin self.transProjection = self.PolarTransform(self) # This one is not aware of rmin self.transPureProjection = self.PolarTransform() # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = self.transScale + self.transProjection + \ (self.transProjectionAffine + self.transAxes) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 1.0 at # the edge of the axis circle. self._xaxis_transform = (self.transPureProjection + self.PolarAffine( IdentityTransform(), Bbox.unit()) + self.transAxes) # The theta labels are moved from radius == 0.0 to radius == 1.1 self._theta_label1_position = Affine2D().translate(0.0, 1.1) self._xaxis_text1_transform = (self._theta_label1_position + self._xaxis_transform) self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1) self._xaxis_text2_transform = (self._theta_label2_position + self._xaxis_transform) # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to # 2pi. self._yaxis_transform = (Affine2D().scale(np.pi * 2.0, 1.0) + self.transData) # The r-axis labels are put at an angle and padded in the r-direction self._r_label1_position = ScaledTranslation( 22.5, self._rpad, blended_transform_factory(Affine2D(), BboxTransformToMaxOnly(self.viewLim))) self._yaxis_text1_transform = (self._r_label1_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform) self._r_label2_position = ScaledTranslation( 22.5, -self._rpad, blended_transform_factory(Affine2D(), BboxTransformToMaxOnly(self.viewLim))) self._yaxis_text2_transform = (self._r_label2_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform)
def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) # data. This one is aware of rmin self.transProjection = self.PolarTransform(self) # This one is not aware of rmin self.transPureProjection = self.PolarTransform(self, use_rmin=False) # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = self.transScale + self.transProjection + (self.transProjectionAffine + self.transAxes) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 1.0 at # the edge of the axis circle. self._xaxis_transform = ( self.transPureProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes ) # The theta labels are moved from radius == 0.0 to radius == 1.1 self._theta_label1_position = Affine2D().translate(0.0, 1.1) self._xaxis_text1_transform = self._theta_label1_position + self._xaxis_transform self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1) self._xaxis_text2_transform = self._theta_label2_position + self._xaxis_transform # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to # 2pi. self._yaxis_transform = Affine2D().scale(np.pi * 2.0, 1.0) + self.transData # The r-axis labels are put at an angle and padded in the r-direction self._r_label1_position = ScaledTranslation( 22.5, self._rpad, blended_transform_factory(Affine2D(), BboxTransformToMaxOnly(self.viewLim)) ) self._yaxis_text1_transform = ( self._r_label1_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform ) self._r_label2_position = ScaledTranslation( 22.5, -self._rpad, blended_transform_factory(Affine2D(), BboxTransformToMaxOnly(self.viewLim)) ) self._yaxis_text2_transform = ( self._r_label2_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform )
def add_letter(ax: Axes = None, offset: float = 0, offset2: float = 0, letter: str = None): """ add a letter indicating which subplot it is to the given figure """ global letter_index from matplotlib.transforms import Affine2D, ScaledTranslation # get the axes if ax is None: ax = plt.gca() # get the figure fig = ax.figure # get the font properties for figure letters font = get_letter_font_prop() # if no letter is given if letter is None: # use the letter_format from the font letter = font.letter_format # and add a letter given the current letter_index letter = letter.replace("a", chr(ord("a") + letter_index)) letter = letter.replace("A", chr(ord("A") + letter_index)) # increase the letter index letter_index += 1 # add a transform that gives the coordinates relative to the left top corner of the axes in cm transform = Affine2D().scale(1 / 2.54, 1 / 2.54) + fig.dpi_scale_trans + ScaledTranslation(0, 1, ax.transAxes) # add a text a the given position ax.text(-0.5+offset, offset2, letter, fontproperties=font, transform=transform, ha="center", va="bottom", picker=True)
def setup_xticklabels(self): """Setup the xtick labels.""" # Labels are placed manually because this is around 25% faster than # using the minor ticks. xticks_info = self.make_xticks_info() self.ax1.set_xticks(xticks_info[0]) for i in range(len(self.xlabels)): self.xlabels[i].remove() padding = ScaledTranslation(0, -5 / 72, self.dpi_scale_trans) self.xlabels = [] for i in range(len(xticks_info[1])): new_label = self.ax1.text(xticks_info[1][i], 0, xticks_info[2][i], rotation=45, va='top', ha='right', fontsize=10, transform=self.ax1.transData + padding) self.xlabels.append(new_label)
def auto_shift(offset): """ Return a y-offset coordinate transform for the current axes. Each call to auto_shift increases the y-offset for the next line by the given number of points (with 72 points per inch). Example:: from matplotlib import pyplot as plt from bumps.plotutil import auto_shift trans = auto_shift(plt.gca()) plot(x, y, trans=trans) """ from matplotlib.transforms import ScaledTranslation import pylab ax = pylab.gca() if ax.lines and hasattr(ax, '_auto_shift'): ax._auto_shift += offset else: ax._auto_shift = 0 trans = pylab.gca().transData if ax._auto_shift: trans += ScaledTranslation(0, ax._auto_shift / 72., pylab.gcf().dpi_scale_trans) return trans
def __init__(self, axes, helper, offset=None, axis_direction="bottom", **kw): """ *axes* : axes *helper* : an AxisArtistHelper instance. """ #axes is also used to follow the axis attribute (tick color, etc). super().__init__(**kw) self.axes = axes self._axis_artist_helper = helper if offset is None: offset = (0, 0) self.dpi_transform = Affine2D() self.offset_transform = ScaledTranslation(offset[0], offset[1], self.dpi_transform) self._label_visible = True self._majortick_visible = True self._majorticklabel_visible = True self._minortick_visible = True self._minorticklabel_visible = True #if self._axis_artist_helper._loc in ["left", "right"]: if axis_direction in ["left", "right"]: axis_name = "ytick" self.axis = axes.yaxis else: axis_name = "xtick" self.axis = axes.xaxis self._axisline_style = None self._axis_direction = axis_direction self._init_line() self._init_ticks(axis_name, **kw) self._init_offsetText(axis_direction) self._init_label() self.set_zorder(self.ZORDER) self._rotate_label_along_line = False # axis direction self._tick_add_angle = 180. self._ticklabel_add_angle = 0. self._axislabel_add_angle = 0. self.set_axis_direction(axis_direction)
def __init__(self, parent_axes=None, transform=None, coord_index=None, coord_type='scalar', coord_wrap=None, frame=None): # Keep a reference to the parent axes and the transform self.parent_axes = parent_axes self.transform = transform self.coord_index = coord_index self.coord_type = coord_type self.frame = frame if coord_type == 'longitude' and coord_wrap is None: self.coord_wrap = 360 elif coord_type != 'longitude' and coord_wrap is not None: raise NotImplementedError( 'coord_wrap is not yet supported for non-longitude coordinates' ) else: self.coord_wrap = coord_wrap # Initialize tick formatter/locator if coord_type == 'scalar': self._formatter_locator = ScalarFormatterLocator() elif coord_type in ['longitude', 'latitude']: self._formatter_locator = AngleFormatterLocator() else: raise ValueError( "coord_type should be one of 'scalar', 'longitude', or 'latitude'" ) # Initialize ticks self.dpi_transform = Affine2D() self.offset_transform = ScaledTranslation(0, 0, self.dpi_transform) self.ticks = Ticks(transform=parent_axes.transData + self.offset_transform) # Initialize tick labels self.ticklabels = TickLabels( transform=None, # display coordinates figure=parent_axes.get_figure()) # Initialize axis labels self.axislabels = AxisLabels( self.frame, transform=None, # display coordinates figure=parent_axes.get_figure()) # Initialize container for the grid lines self.grid_lines = [] self.grid_lines_kwargs = { 'visible': False, 'facecolor': 'none', 'transform': self.parent_axes.transData }
def __init__(self, parent_axes=None, parent_map=None, transform=None, coord_index=None, coord_type='scalar', coord_unit=None, coord_wrap=None, frame=None, format_unit=None): # Keep a reference to the parent axes and the transform self.parent_axes = parent_axes self.parent_map = parent_map self.transform = transform self.coord_index = coord_index self.coord_unit = coord_unit self.format_unit = format_unit self.frame = frame self.set_coord_type(coord_type, coord_wrap) # Initialize ticks self.dpi_transform = Affine2D() self.offset_transform = ScaledTranslation(0, 0, self.dpi_transform) self.ticks = Ticks(transform=parent_axes.transData + self.offset_transform) # Initialize tick labels self.ticklabels = TickLabels( self.frame, transform=None, # display coordinates figure=parent_axes.get_figure()) self.ticks.display_minor_ticks(rcParams['xtick.minor.visible']) self.minor_frequency = 5 # Initialize axis labels self.axislabels = AxisLabels( self.frame, transform=None, # display coordinates figure=parent_axes.get_figure()) # Initialize container for the grid lines self.grid_lines = [] # Initialize grid style. Take defaults from matplotlib.rcParams. # Based on matplotlib.axis.YTick._get_gridline. self.grid_lines_kwargs = { 'visible': False, 'facecolor': 'none', 'edgecolor': rcParams['grid.color'], 'linestyle': LINES_TO_PATCHES_LINESTYLE[rcParams['grid.linestyle']], 'linewidth': rcParams['grid.linewidth'], 'alpha': rcParams['grid.alpha'], 'transform': self.parent_axes.transData }
def __init__(self, axes, helper, offset=None, major_tick_size=None, major_tick_pad=None, minor_tick_size=None, minor_tick_pad=None, **kw): """ axes is also used to follow the axis attribute (tick color, etc). """ super(AxisArtist, self).__init__(**kw) self.axes = axes self._axis_artist_helper = helper if offset is None: offset = (0, 0) self.dpi_transform = Affine2D() self.offset_transform = ScaledTranslation(offset[0], offset[1], self.dpi_transform) self._label_visible = True self._majortick_visible = True self._majorticklabel_visible = True self._minortick_visible = True self._minorticklabel_visible = True if self._axis_artist_helper.label_direction in ["left", "right"]: axis_name = "ytick" self.axis = axes.yaxis else: axis_name = "xtick" self.axis = axes.xaxis if major_tick_size is None: self.major_tick_size = rcParams['%s.major.size' % axis_name] if major_tick_pad is None: self.major_tick_pad = rcParams['%s.major.pad' % axis_name] if minor_tick_size is None: self.minor_tick_size = rcParams['%s.minor.size' % axis_name] if minor_tick_pad is None: self.minor_tick_pad = rcParams['%s.minor.pad' % axis_name] self._axisline_style = None self._init_line() self._init_ticks() self._init_offsetText(self._axis_artist_helper.label_direction) self._init_label() self.set_zorder(self.ZORDER) self._rotate_label_along_line = False
def draw_figure_title(self): """Draw the title of the figure.""" labelDB = LabelDatabase(self.language) if self.isGraphTitle: # Set the text and position of the title. if self.meteo_on: offset = ScaledTranslation(0, 7/72, self.dpi_scale_trans) self.text1.set_text( labelDB.station_meteo % (self.name_meteo, self.dist)) self.text1.set_transform(self.ax0.transAxes + offset) dy = 30 if self.meteo_on else 7 offset = ScaledTranslation(0, dy/72, self.dpi_scale_trans) self.figTitle.set_text(labelDB.title % self.wldset['Well']) self.figTitle.set_transform(self.ax0.transAxes + offset) # Set whether the title is visible or not. self.text1.set_visible(self.meteo_on and self.isGraphTitle) self.figTitle.set_visible(self.isGraphTitle)
def __init__(self, parent_axes=None, parent_map=None, transform=None, coord_index=None, coord_type='scalar', coord_unit=None, coord_wrap=None, frame=None): # Keep a reference to the parent axes and the transform self.parent_axes = parent_axes self.parent_map = parent_map self.transform = transform self.coord_index = coord_index self.coord_unit = coord_unit self.frame = frame self.set_coord_type(coord_type, coord_wrap) # Initialize ticks self.dpi_transform = Affine2D() self.offset_transform = ScaledTranslation(0, 0, self.dpi_transform) self.ticks = Ticks(transform=parent_axes.transData + self.offset_transform) # Initialize tick labels self.ticklabels = TickLabels(self.frame, transform=None, # display coordinates figure=parent_axes.get_figure()) self.ticks.display_minor_ticks(False) self.minor_frequency = 5 # Initialize axis labels self.axislabels = AxisLabels(self.frame, transform=None, # display coordinates figure=parent_axes.get_figure()) # Initialize container for the grid lines self.grid_lines = [] # Initialize grid style. Take defaults from matplotlib.rcParams. # Based on matplotlib.axis.YTick._get_gridline. # # Matplotlib's gridlines use Line2D, but ours use PathPatch. # Patches take a slightly different format of linestyle argument. lines_to_patches_linestyle = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted', 'none': 'none', 'None': 'none', ' ': 'none', '': 'none'} self.grid_lines_kwargs = {'visible': False, 'facecolor': 'none', 'edgecolor': rcParams['grid.color'], 'linestyle': lines_to_patches_linestyle[rcParams['grid.linestyle']], 'linewidth': rcParams['grid.linewidth'], 'alpha': rcParams.get('grid.alpha', 1.0), 'transform': self.parent_axes.transData}
def __init__(self, axes, helper, offset=None, axis_direction="bottom", **kwargs): """ Parameters ---------- axes : `mpl_toolkits.axisartist.axislines.Axes` helper : `~mpl_toolkits.axisartist.axislines.AxisArtistHelper` """ #axes is also used to follow the axis attribute (tick color, etc). super().__init__(**kwargs) self.axes = axes self._axis_artist_helper = helper if offset is None: offset = (0, 0) self.offset_transform = ScaledTranslation( *offset, Affine2D().scale(1 / 72) # points to inches. + self.axes.figure.dpi_scale_trans) if axis_direction in ["left", "right"]: axis_name = "ytick" self.axis = axes.yaxis else: axis_name = "xtick" self.axis = axes.xaxis self._axisline_style = None self._axis_direction = axis_direction self._init_line() self._init_ticks(axis_name, **kwargs) self._init_offsetText(axis_direction) self._init_label() self.set_zorder(self.ZORDER) self._rotate_label_along_line = False # axis direction self._tick_add_angle = 180. self._ticklabel_add_angle = 0. self._axislabel_add_angle = 0. self.set_axis_direction(axis_direction)
def plotEllipse(ax, x, y, semi_major, semi_minor, angle=0, fill=False, lw=3, log=False, **kwargs): from matplotlib.patches import Ellipse from matplotlib.transforms import ScaledTranslation if log: # use the axis scale tform to figure out how far to translate circ_offset = ScaledTranslation(x, y, ax.transScale) # construct the composite tform circ_tform = circ_offset + ax.transLimits + ax.transAxes # create the circle centred on the origin, apply the composite tform circ = Ellipse((0, 0), 2 * semi_major, 2 * semi_minor, angle=angle, fill=fill, lw=lw, transform=circ_tform, **kwargs) ax.add_artist(circ) else: return ax.add_artist( Ellipse((x, y), semi_major, semi_minor, angle=angle, fill=fill, lw=lw, **kwargs))
def setNode(self, node): if self.artist_ != None: self.artist_[0].remove() self.artist_[1].remove() if self.parent_ == None: return [m11, m12, m13, m21, m22, m23] = node.getTransformation() #https://matplotlib.org/3.1.0/tutorials/advanced/transforms_tutorial.html mtx = np.array([[m11, m12, 0], [m21, m22, 0], [0, 0, 1]]) refcs = Affine2D(matrix=mtx) xx, xy = refcs.transform((0.0, 1.0)) yx, yy = refcs.transform((1.0, 0.0)) self.ox_ = m13 self.oy_ = m23 axes = self.parent_.axes_ figure = self.parent_.fig_ trans = (figure.dpi_scale_trans + ScaledTranslation(self.ox_, self.oy_, axes.transData)) cx = axes.arrow(0, 0, xx, xy, head_width=0.1, head_length=0.2, fc='b', ec='b', transform=trans) cy = axes.arrow(0, 0, yx, yy, head_width=0.1, head_length=0.2, fc='r', ec='r', transform=trans) self.artist_ = (cx, cy)
def plot_legend(self): """Plot the legend of the figure.""" ax = self.figure.axes[2] # bbox transform : padding = ScaledTranslation(5 / 72, -5 / 72, self.figure.dpi_scale_trans) transform = ax.transAxes + padding # Define proxy artists : colors = ColorsReader() colors.load_colors_db() rec1 = Rectangle((0, 0), 1, 1, fc=colors.rgb['Snow'], ec='none') rec2 = Rectangle((0, 0), 1, 1, fc=colors.rgb['Rain'], ec='none') # Define the legend labels and markers : lines = [ax.lines[0], ax.lines[1], ax.lines[2], rec2, rec1] labels = [ self.fig_labels.Tmax, self.fig_labels.Tavg, self.fig_labels.Tmin, self.fig_labels.rain, self.fig_labels.snow ] # Plot the legend : leg = ax.legend(lines, labels, numpoints=1, fontsize=13, borderaxespad=0, loc='upper left', borderpad=0, bbox_to_anchor=(0, 1), bbox_transform=transform) leg.draw_frame(False)
class PolarAxes(Axes): """ A polar graph projection, where the input dimensions are *theta*, *r*. Theta starts pointing east and goes anti-clockwise. """ name = 'polar' def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. The following optional kwargs are supported: - *resolution*: The number of points of interpolation between each pair of data points. Set to 1 to disable interpolation. """ self.resolution = kwargs.pop('resolution', 1) self._default_theta_offset = kwargs.pop('theta_offset', 0) self._default_theta_direction = kwargs.pop('theta_direction', 1) if self.resolution not in (None, 1): warnings.warn( """The resolution kwarg to Polar plots is now ignored. If you need to interpolate data points, consider running cbook.simple_linear_interpolation on the data before passing to matplotlib.""") Axes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() __init__.__doc__ = Axes.__init__.__doc__ def cla(self): Axes.cla(self) self.title.set_y(1.05) self.xaxis.set_major_formatter(self.ThetaFormatter()) self.xaxis.isDefault_majfmt = True angles = np.arange(0.0, 360.0, 45.0) self.set_thetagrids(angles) self.yaxis.set_major_locator(self.RadialLocator(self.yaxis.get_major_locator())) self.grid(rcParams['polaraxes.grid']) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? self.set_theta_offset(self._default_theta_offset) self.set_theta_direction(self._default_theta_direction) def _init_axis(self): "move this out of __init__ because non-separable axes don't use it" self.xaxis = maxis.XAxis(self) self.yaxis = maxis.YAxis(self) # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla() # results in weird artifacts. Therefore we disable this for # now. # self.spines['polar'].register_axis(self.yaxis) self._update_transScale() def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) # data. This one is aware of rmin self.transProjection = self.PolarTransform(self) # This one is not aware of rmin self.transPureProjection = self.PolarTransform(self, use_rmin=False) # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = self.transScale + self.transProjection + \ (self.transProjectionAffine + self.transAxes) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 1.0 at # the edge of the axis circle. self._xaxis_transform = ( self.transPureProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes) # The theta labels are moved from radius == 0.0 to radius == 1.1 self._theta_label1_position = Affine2D().translate(0.0, 1.1) self._xaxis_text1_transform = ( self._theta_label1_position + self._xaxis_transform) self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1) self._xaxis_text2_transform = ( self._theta_label2_position + self._xaxis_transform) # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to # 2pi. self._yaxis_transform = ( Affine2D().scale(np.pi * 2.0, 1.0) + self.transData) # The r-axis labels are put at an angle and padded in the r-direction self._r_label_position = ScaledTranslation( 22.5, 0.0, Affine2D()) self._yaxis_text_transform = ( self._r_label_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform ) def get_xaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return self._xaxis_text1_transform, 'center', 'center' def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'center', 'center' def get_yaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._yaxis_transform def get_yaxis_text1_transform(self, pad): angle = self._r_label_position.to_values()[4] if angle < 90.: return self._yaxis_text_transform, 'bottom', 'left' elif angle < 180.: return self._yaxis_text_transform, 'bottom', 'right' elif angle < 270.: return self._yaxis_text_transform, 'top', 'right' else: return self._yaxis_text_transform, 'top', 'left' def get_yaxis_text2_transform(self, pad): angle = self._r_label_position.to_values()[4] if angle < 90.: return self._yaxis_text_transform, 'top', 'right' elif angle < 180.: return self._yaxis_text_transform, 'top', 'left' elif angle < 270.: return self._yaxis_text_transform, 'bottom', 'left' else: return self._yaxis_text_transform, 'bottom', 'right' def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): return {'polar':mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)} def set_rmax(self, rmax): self.viewLim.y1 = rmax def get_rmax(self): return self.viewLim.ymax def set_rmin(self, rmin): self.viewLim.y0 = rmin def get_rmin(self): return self.viewLim.ymin def set_theta_offset(self, offset): """ Set the offset for the location of 0 in radians. """ self._theta_offset = offset def get_theta_offset(self): """ Get the offset for the location of 0 in radians. """ return self._theta_offset def set_theta_zero_location(self, loc): """ Sets the location of theta's zero. (Calls set_theta_offset with the correct value in radians under the hood.) May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE". """ mapping = { 'N': np.pi * 0.5, 'NW': np.pi * 0.75, 'W': np.pi, 'SW': np.pi * 1.25, 'S': np.pi * 1.5, 'SE': np.pi * 1.75, 'E': 0, 'NE': np.pi * 0.25 } return self.set_theta_offset(mapping[loc]) def set_theta_direction(self, direction): """ Set the direction in which theta increases. clockwise, -1: Theta increases in the clockwise direction counterclockwise, anticlockwise, 1: Theta increases in the counterclockwise direction """ if direction in ('clockwise',): self._direction = -1 elif direction in ('counterclockwise', 'anticlockwise'): self._direction = 1 elif direction in (1, -1): self._direction = direction else: raise ValueError("direction must be 1, -1, clockwise or counterclockwise") def get_theta_direction(self): """ Get the direction in which theta increases. -1: Theta increases in the clockwise direction 1: Theta increases in the counterclockwise direction """ return self._direction def set_rlim(self, *args, **kwargs): if 'rmin' in kwargs: kwargs['ymin'] = kwargs.pop('rmin') if 'rmax' in kwargs: kwargs['ymax'] = kwargs.pop('rmax') return self.set_ylim(*args, **kwargs) def set_yscale(self, *args, **kwargs): Axes.set_yscale(self, *args, **kwargs) self.yaxis.set_major_locator( self.RadialLocator(self.yaxis.get_major_locator())) def set_rscale(self, *args, **kwargs): return Axes.set_yscale(self, *args, **kwargs) def set_rticks(self, *args, **kwargs): return Axes.set_yticks(self, *args, **kwargs) @docstring.dedent_interpd def set_thetagrids(self, angles, labels=None, frac=None, fmt=None, **kwargs): """ Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not None, is a ``len(angles)`` list of strings of the labels to use at each angle. If *labels* is None, the labels will be ``fmt %% angle`` *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). Eg. 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data angles = self.convert_yunits(angles) angles = np.asarray(angles, np.float_) self.set_xticks(angles * (np.pi / 180.0)) if labels is not None: self.set_xticklabels(labels) elif fmt is not None: self.xaxis.set_major_formatter(FormatStrFormatter(fmt)) if frac is not None: self._theta_label1_position.clear().translate(0.0, frac) self._theta_label2_position.clear().translate(0.0, 1.0 / frac) for t in self.xaxis.get_ticklabels(): t.update(kwargs) return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels() @docstring.dedent_interpd def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs): """ Set the radial locations and labels of the *r* grids. The labels will appear at radial distances *radii* at the given *angle* in degrees. *labels*, if not None, is a ``len(radii)`` list of strings of the labels to use at each radius. If *labels* is None, the built-in formatter will be used. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data radii = self.convert_xunits(radii) radii = np.asarray(radii) rmin = radii.min() if rmin <= 0: raise ValueError('radial grids must be strictly positive') self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) elif fmt is not None: self.yaxis.set_major_formatter(FormatStrFormatter(fmt)) if angle is None: angle = self._r_label_position.to_values()[4] self._r_label_position._t = (angle, 0.0) self._r_label_position.invalidate() for t in self.yaxis.get_ticklabels(): t.update(kwargs) return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels() def set_xscale(self, scale, *args, **kwargs): if scale != 'linear': raise NotImplementedError("You can not set the xscale on a polar plot.") def set_xlim(self, *args, **kargs): # The xlim is fixed, no matter what you do self.viewLim.intervalx = (0.0, np.pi * 2.0) def format_coord(self, theta, r): """ Return a format string formatting the coordinate using Unicode characters. """ theta /= math.pi # \u03b8: lower-case theta # \u03c0: lower-case pi # \u00b0: degree symbol return u'\u03b8=%0.3f\u03c0 (%0.3f\u00b0), r=%0.3f' % (theta, theta * 180.0, r) def get_data_ratio(self): ''' Return the aspect ratio of the data itself. For a polar plot, this should always be 1.0 ''' return 1.0 ### Interactive panning def can_zoom(self): """ Return *True* if this axes supports the zoom box button functionality. Polar axes do not support zoom boxes. """ return False def can_pan(self) : """ Return *True* if this axes supports the pan/zoom button functionality. For polar axes, this is slightly misleading. Both panning and zooming are performed by the same button. Panning is performed in azimuth while zooming is done along the radial. """ return True def start_pan(self, x, y, button): angle = np.deg2rad(self._r_label_position.to_values()[4]) mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if t >= angle - epsilon and t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = cbook.Bunch( rmax = self.get_rmax(), trans = self.transData.frozen(), trans_inverse = self.transData.inverted().frozen(), r_label_angle = self._r_label_position.to_values()[4], x = x, y = y, mode = mode ) def end_pan(self): del self._pan_start def drag_pan(self, button, key, x, y): p = self._pan_start if p.mode == 'drag_r_labels': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) # Deal with theta dt0 = t - startt dt1 = startt - t if abs(dt1) < abs(dt0): dt = abs(dt1) * sign(dt0) * -1.0 else: dt = dt0 * -1.0 dt = (dt / np.pi) * 180.0 self._r_label_position._t = (p.r_label_angle - dt, 0.0) self._r_label_position.invalidate() trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0) trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0) for t in self.yaxis.majorTicks + self.yaxis.minorTicks: t.label1.set_va(vert1) t.label1.set_ha(horiz1) t.label2.set_va(vert2) t.label2.set_ha(horiz2) elif p.mode == 'zoom': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) dr = r - startr # Deal with r scale = r / startr self.set_rmax(p.rmax / scale)
########## simulations without binding ########## plt.figure("0bind", figsize=figsize) a, t, ood = fields.get("eventspara_nobind", "a", "t", "ood") a, t, success = np.array(a), np.array(t), np.array(ood) == 0 plt.scatter(t[~success], a[~success], **s_fail) plt.scatter(t[success], a[success], **s_success) plt.scatter(t_exp, a_exp, **s_experiment) ax = plt.gca() format_ticks(ax) plt.legend(loc="lower left", scatterpoints=3, frameon=False, borderaxespad=0.2, handletextpad=0.4) # encircle long bindings offset = ScaledTranslation(18, 27, ax.transScale) tform = offset + ax.transLimits + ax.transAxes ell = mpatch.Ellipse((0, 0), 1.8, 10, angle=0.0, transform=tform, fc="None", ec=long_bind_color) ax.add_patch(ell) plt.text(15, 21, "Assumed\n long bindings", color=long_bind_color, horizontalalignment="center") ########## simulations with one binding ########## plt.figure("1bind", figsize=figsize) a, t, ood = fields.get("eventsnew_onlyone_2_", "a", "t", "ood") a, t, success = np.array(a), np.array(t), np.array(ood) == 0 plt.scatter(t[~success], a[~success], **s_fail) plt.scatter(t[success], a[success], **s_success) plt.scatter(t_exp, a_exp, **s_experiment)
def __init__(self, lang='English'): super(BRFFigure, self).__init__() lang = lang if lang.lower() in FigureLabels.LANGUAGES else 'English' self.__figlang = lang self.__figlabels = FigureLabels(lang) # ---- Figure Creation fig_width = 8 fig_height = 5 self.set_size_inches(fig_width, fig_height) self.patch.set_facecolor('white') left_margin = 0.8 right_margin = 0.25 bottom_margin = 0.75 top_margin = 0.25 # ---- Axe Setup ax = self.add_axes([ left_margin / fig_width, bottom_margin / fig_height, 1 - (left_margin + right_margin) / fig_width, 1 - (bottom_margin + top_margin) / fig_height ], zorder=1) ax.set_visible(False) # ---- Ticks Setup ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.tick_params(axis='both', which='major', direction='out', gridOn=True) # ---- Artists Init self.line, = ax.plot([], [], ls='-', color='blue', linewidth=1.5, zorder=20, clip_on=True) self.markers, = ax.plot([], [], color='0.1', mec='0.1', marker='.', ls='None', ms=5, zorder=30, mew=1, clip_on=False) self.errbar, = ax.plot([], []) offset = ScaledTranslation(0, -5 / 72, self.dpi_scale_trans) self.title = ax.text(0.5, 1, '', ha='center', va='top', fontsize=14, transform=ax.transAxes + offset)
def _T(self): F = self.plotter.figure.dpi_scale_trans S = ScaledTranslation(self.point[0], self.point[1], self.plotter.axes.transData) T = F + S return T
class PolarAxes(Axes): """ A polar graph projection, where the input dimensions are *theta*, *r*. Theta starts pointing east and goes anti-clockwise. """ name = 'polar' class PolarTransform(Transform): """ The base polar transform. This handles projection *theta* and *r* into Cartesian coordinate space *x* and *y*, but does not perform the ultimate affine transformation into the correct position. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, axis=None, use_rmin=True): Transform.__init__(self) self._axis = axis self._use_rmin = use_rmin def transform(self, tr): xy = np.empty(tr.shape, np.float_) if self._axis is not None: if self._use_rmin: rmin = self._axis.viewLim.ymin else: rmin = 0 theta_offset = self._axis.get_theta_offset() theta_direction = self._axis.get_theta_direction() else: rmin = 0 theta_offset = 0 theta_direction = 1 t = tr[:, 0:1] r = tr[:, 1:2] x = xy[:, 0:1] y = xy[:, 1:2] t *= theta_direction t += theta_offset if rmin != 0: r = r - rmin mask = r < 0 x[:] = np.where(mask, np.nan, r * np.cos(t)) y[:] = np.where(mask, np.nan, r * np.sin(t)) else: x[:] = r * np.cos(t) y[:] = r * np.sin(t) return xy transform.__doc__ = Transform.transform.__doc__ transform_non_affine = transform transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def transform_path(self, path): vertices = path.vertices if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]: return Path(self.transform(vertices), path.codes) ipath = path.interpolated(path._interpolation_steps) return Path(self.transform(ipath.vertices), ipath.codes) transform_path.__doc__ = Transform.transform_path.__doc__ transform_path_non_affine = transform_path transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__ def inverted(self): return PolarAxes.InvertedPolarTransform(self._axis, self._use_rmin) inverted.__doc__ = Transform.inverted.__doc__ class PolarAffine(Affine2DBase): """ The affine part of the polar projection. Scales the output so that maximum radius rests on the edge of the axes circle. """ def __init__(self, scale_transform, limits): """ *limits* is the view limit of the data. The only part of its bounds that is used is ymax (for the radius maximum). The theta range is always fixed to (0, 2pi). """ Affine2DBase.__init__(self) self._scale_transform = scale_transform self._limits = limits self.set_children(scale_transform, limits) self._mtx = None def get_matrix(self): if self._invalid: limits_scaled = self._limits.transformed(self._scale_transform) yscale = limits_scaled.ymax - limits_scaled.ymin affine = Affine2D() \ .scale(0.5 / yscale) \ .translate(0.5, 0.5) self._mtx = affine.get_matrix() self._inverted = None self._invalid = 0 return self._mtx get_matrix.__doc__ = Affine2DBase.get_matrix.__doc__ class InvertedPolarTransform(Transform): """ The inverse of the polar transform, mapping Cartesian coordinate space *x* and *y* back to *theta* and *r*. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, axis=None, use_rmin=True): Transform.__init__(self) self._axis = axis self._use_rmin = use_rmin def transform(self, xy): if self._axis is not None: if self._use_rmin: rmin = self._axis.viewLim.ymin else: rmin = 0 theta_offset = self._axis.get_theta_offset() theta_direction = self._axis.get_theta_direction() else: rmin = 0 theta_offset = 0 theta_direction = 1 x = xy[:, 0:1] y = xy[:, 1:] r = np.sqrt(x*x + y*y) theta = np.arccos(x / r) theta = np.where(y < 0, 2 * np.pi - theta, theta) theta -= theta_offset theta *= theta_direction r += rmin return np.concatenate((theta, r), 1) transform.__doc__ = Transform.transform.__doc__ def inverted(self): return PolarAxes.PolarTransform(self._axis, self._use_rmin) inverted.__doc__ = Transform.inverted.__doc__ class ThetaFormatter(Formatter): """ Used to format the *theta* tick labels. Converts the native unit of radians into degrees and adds a degree symbol. """ def __call__(self, x, pos=None): # \u00b0 : degree symbol if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: return r"$%0.0f^\circ$" % ((x / np.pi) * 180.0) else: # we use unicode, rather than mathtext with \circ, so # that it will work correctly with any arbitrary font # (assuming it has a degree sign), whereas $5\circ$ # will only work correctly with one of the supported # math fonts (Computer Modern and STIX) return u"%0.0f\u00b0" % ((x / np.pi) * 180.0) class RadialLocator(Locator): """ Used to locate radius ticks. Ensures that all ticks are strictly positive. For all other tasks, it delegates to the base :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base): self.base = base def __call__(self): ticks = self.base() return [x for x in ticks if x > 0] def autoscale(self): return self.base.autoscale() def pan(self, numsteps): return self.base.pan(numsteps) def zoom(self, direction): return self.base.zoom(direction) def refresh(self): return self.base.refresh() def view_limits(self, vmin, vmax): vmin, vmax = self.base.view_limits(vmin, vmax) return 0, vmax def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. The following optional kwargs are supported: - *resolution*: The number of points of interpolation between each pair of data points. Set to 1 to disable interpolation. """ self.resolution = kwargs.pop('resolution', None) if self.resolution not in (None, 1): warnings.warn( """The resolution kwarg to Polar plots is now ignored. If you need to interpolate data points, consider running cbook.simple_linear_interpolation on the data before passing to matplotlib.""") Axes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() __init__.__doc__ = Axes.__init__.__doc__ def cla(self): Axes.cla(self) self.title.set_y(1.05) self.xaxis.set_major_formatter(self.ThetaFormatter()) self.xaxis.isDefault_majfmt = True angles = np.arange(0.0, 360.0, 45.0) self.set_thetagrids(angles) self.yaxis.set_major_locator(self.RadialLocator(self.yaxis.get_major_locator())) self.grid(rcParams['polaraxes.grid']) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? self.set_theta_offset(0) self.set_theta_direction(1) def _init_axis(self): "move this out of __init__ because non-separable axes don't use it" self.xaxis = maxis.XAxis(self) self.yaxis = maxis.YAxis(self) # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla() # results in weird artifacts. Therefore we disable this for # now. # self.spines['polar'].register_axis(self.yaxis) self._update_transScale() def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) # data. This one is aware of rmin self.transProjection = self.PolarTransform(self) # This one is not aware of rmin self.transPureProjection = self.PolarTransform(self, use_rmin=False) # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = self.transScale + self.transProjection + \ (self.transProjectionAffine + self.transAxes) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 1.0 at # the edge of the axis circle. self._xaxis_transform = ( self.transPureProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes) # The theta labels are moved from radius == 0.0 to radius == 1.1 self._theta_label1_position = Affine2D().translate(0.0, 1.1) self._xaxis_text1_transform = ( self._theta_label1_position + self._xaxis_transform) self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1) self._xaxis_text2_transform = ( self._theta_label2_position + self._xaxis_transform) # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to # 2pi. self._yaxis_transform = ( Affine2D().scale(np.pi * 2.0, 1.0) + self.transData) # The r-axis labels are put at an angle and padded in the r-direction self._r_label_position = ScaledTranslation( 22.5, 0.0, Affine2D()) self._yaxis_text_transform = ( self._r_label_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform ) def get_xaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return self._xaxis_text1_transform, 'center', 'center' def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'center', 'center' def get_yaxis_transform(self,which='grid'): assert which in ['tick1','tick2','grid'] return self._yaxis_transform def get_yaxis_text1_transform(self, pad): angle = self._r_label_position.to_values()[4] if angle < 90.: return self._yaxis_text_transform, 'bottom', 'left' elif angle < 180.: return self._yaxis_text_transform, 'bottom', 'right' elif angle < 270.: return self._yaxis_text_transform, 'top', 'right' else: return self._yaxis_text_transform, 'top', 'left' def get_yaxis_text2_transform(self, pad): angle = self._r_label_position.to_values()[4] if angle < 90.: return self._yaxis_text_transform, 'top', 'right' elif angle < 180.: return self._yaxis_text_transform, 'top', 'left' elif angle < 270.: return self._yaxis_text_transform, 'bottom', 'left' else: return self._yaxis_text_transform, 'bottom', 'right' def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): return {'polar':mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)} def set_rmax(self, rmax): self.viewLim.y1 = rmax def get_rmax(self): return self.viewLim.ymax def set_rmin(self, rmin): self.viewLim.y0 = rmin def get_rmin(self): return self.viewLim.ymin def set_theta_offset(self, offset): """ Set the offset for the location of 0 in radians. """ self._theta_offset = offset def get_theta_offset(self): """ Get the offset for the location of 0 in radians. """ return self._theta_offset def set_theta_zero_location(self, loc): """ Sets the location of theta's zero. (Calls set_theta_offset with the correct value in radians under the hood.) May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE". """ mapping = { 'N': np.pi * 0.5, 'NW': np.pi * 0.75, 'W': np.pi, 'SW': np.pi * 1.25, 'S': np.pi * 1.5, 'SE': np.pi * 1.75, 'E': 0, 'NE': np.pi * 0.25 } return self.set_theta_offset(mapping[loc]) def set_theta_direction(self, direction): """ Set the direction in which theta increases. clockwise, -1: Theta increases in the clockwise direction counterclockwise, anticlockwise, 1: Theta increases in the counterclockwise direction """ if direction in ('clockwise',): self._direction = -1 elif direction in ('counterclockwise', 'anticlockwise'): self._direction = 1 elif direction in (1, -1): self._direction = direction else: raise ValueError("direction must be 1, -1, clockwise or counterclockwise") def get_theta_direction(self): """ Get the direction in which theta increases. -1: Theta increases in the clockwise direction 1: Theta increases in the counterclockwise direction """ return self._direction def set_rlim(self, *args, **kwargs): if 'rmin' in kwargs: kwargs['ymin'] = kwargs.pop('rmin') if 'rmax' in kwargs: kwargs['ymax'] = kwargs.pop('rmax') return self.set_ylim(*args, **kwargs) def set_yscale(self, *args, **kwargs): Axes.set_yscale(self, *args, **kwargs) self.yaxis.set_major_locator( self.RadialLocator(self.yaxis.get_major_locator())) set_rscale = Axes.set_yscale set_rticks = Axes.set_yticks @docstring.dedent_interpd def set_thetagrids(self, angles, labels=None, frac=None, fmt=None, **kwargs): """ Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not None, is a ``len(angles)`` list of strings of the labels to use at each angle. If *labels* is None, the labels will be ``fmt %% angle`` *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). Eg. 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data angles = self.convert_yunits(angles) angles = np.asarray(angles, np.float_) self.set_xticks(angles * (np.pi / 180.0)) if labels is not None: self.set_xticklabels(labels) elif fmt is not None: self.xaxis.set_major_formatter(FormatStrFormatter(fmt)) if frac is not None: self._theta_label1_position.clear().translate(0.0, frac) self._theta_label2_position.clear().translate(0.0, 1.0 / frac) for t in self.xaxis.get_ticklabels(): t.update(kwargs) return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels() @docstring.dedent_interpd def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs): """ Set the radial locations and labels of the *r* grids. The labels will appear at radial distances *radii* at the given *angle* in degrees. *labels*, if not None, is a ``len(radii)`` list of strings of the labels to use at each radius. If *labels* is None, the built-in formatter will be used. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data radii = self.convert_xunits(radii) radii = np.asarray(radii) rmin = radii.min() if rmin <= 0: raise ValueError('radial grids must be strictly positive') self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) elif fmt is not None: self.yaxis.set_major_formatter(FormatStrFormatter(fmt)) if angle is None: angle = self._r_label_position.to_values()[4] self._r_label_position._t = (angle, 0.0) self._r_label_position.invalidate() for t in self.yaxis.get_ticklabels(): t.update(kwargs) return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels() def set_xscale(self, scale, *args, **kwargs): if scale != 'linear': raise NotImplementedError("You can not set the xscale on a polar plot.") def set_xlim(self, *args, **kargs): # The xlim is fixed, no matter what you do self.viewLim.intervalx = (0.0, np.pi * 2.0) def format_coord(self, theta, r): """ Return a format string formatting the coordinate using Unicode characters. """ theta /= math.pi # \u03b8: lower-case theta # \u03c0: lower-case pi # \u00b0: degree symbol return u'\u03b8=%0.3f\u03c0 (%0.3f\u00b0), r=%0.3f' % (theta, theta * 180.0, r) def get_data_ratio(self): ''' Return the aspect ratio of the data itself. For a polar plot, this should always be 1.0 ''' return 1.0 ### Interactive panning def can_zoom(self): """ Return *True* if this axes supports the zoom box button functionality. Polar axes do not support zoom boxes. """ return False def can_pan(self) : """ Return *True* if this axes supports the pan/zoom button functionality. For polar axes, this is slightly misleading. Both panning and zooming are performed by the same button. Panning is performed in azimuth while zooming is done along the radial. """ return True def start_pan(self, x, y, button): angle = np.deg2rad(self._r_label_position.to_values()[4]) mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if t >= angle - epsilon and t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = cbook.Bunch( rmax = self.get_rmax(), trans = self.transData.frozen(), trans_inverse = self.transData.inverted().frozen(), r_label_angle = self._r_label_position.to_values()[4], x = x, y = y, mode = mode ) def end_pan(self): del self._pan_start def drag_pan(self, button, key, x, y): p = self._pan_start if p.mode == 'drag_r_labels': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) # Deal with theta dt0 = t - startt dt1 = startt - t if abs(dt1) < abs(dt0): dt = abs(dt1) * sign(dt0) * -1.0 else: dt = dt0 * -1.0 dt = (dt / np.pi) * 180.0 self._r_label_position._t = (p.r_label_angle - dt, 0.0) self._r_label_position.invalidate() trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0) trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0) for t in self.yaxis.majorTicks + self.yaxis.minorTicks: t.label1.set_va(vert1) t.label1.set_ha(horiz1) t.label2.set_va(vert2) t.label2.set_ha(horiz2) elif p.mode == 'zoom': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) dr = r - startr # Deal with r scale = r / startr self.set_rmax(p.rmax / scale)
class PolarAxes(Axes): """ A polar graph projection, where the input dimensions are *theta*, *r*. Theta starts pointing east and goes anti-clockwise. """ name = 'polar' class PolarTransform(Transform): """ The base polar transform. This handles projection *theta* and *r* into Cartesian coordinate space *x* and *y*, but does not perform the ultimate affine transformation into the correct position. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, axis=None): Transform.__init__(self) self._axis = axis def transform(self, tr): xy = np.empty(tr.shape, np.float_) if self._axis is not None: rmin = self._axis.viewLim.ymin else: rmin = 0 t = tr[:, 0:1] r = tr[:, 1:2] x = xy[:, 0:1] y = xy[:, 1:2] if rmin != 0: r = r - rmin mask = r < 0 x[:] = np.where(mask, np.nan, r * np.cos(t)) y[:] = np.where(mask, np.nan, r * np.sin(t)) else: x[:] = r * np.cos(t) y[:] = r * np.sin(t) return xy transform.__doc__ = Transform.transform.__doc__ transform_non_affine = transform transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def transform_path(self, path): vertices = path.vertices if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]: return Path(self.transform(vertices), path.codes) ipath = path.interpolated(path._interpolation_steps) return Path(self.transform(ipath.vertices), ipath.codes) transform_path.__doc__ = Transform.transform_path.__doc__ transform_path_non_affine = transform_path transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__ def inverted(self): return PolarAxes.InvertedPolarTransform(self._axis) inverted.__doc__ = Transform.inverted.__doc__ class PolarAffine(Affine2DBase): """ The affine part of the polar projection. Scales the output so that maximum radius rests on the edge of the axes circle. """ def __init__(self, scale_transform, limits): """ *limits* is the view limit of the data. The only part of its bounds that is used is ymax (for the radius maximum). The theta range is always fixed to (0, 2pi). """ Affine2DBase.__init__(self) self._scale_transform = scale_transform self._limits = limits self.set_children(scale_transform, limits) self._mtx = None def get_matrix(self): if self._invalid: limits_scaled = self._limits.transformed(self._scale_transform) yscale = limits_scaled.ymax - limits_scaled.ymin affine = Affine2D() \ .scale(0.5 / yscale) \ .translate(0.5, 0.5) self._mtx = affine.get_matrix() self._inverted = None self._invalid = 0 return self._mtx get_matrix.__doc__ = Affine2DBase.get_matrix.__doc__ class InvertedPolarTransform(Transform): """ The inverse of the polar transform, mapping Cartesian coordinate space *x* and *y* back to *theta* and *r*. """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, axis=None): Transform.__init__(self) self._axis = axis def transform(self, xy): x = xy[:, 0:1] y = xy[:, 1:] r = np.sqrt(x * x + y * y) if self._axis is not None: r += self._axis.viewLim.ymin theta = np.arccos(x / r) theta = np.where(y < 0, 2 * np.pi - theta, theta) return np.concatenate((theta, r), 1) transform.__doc__ = Transform.transform.__doc__ def inverted(self): return PolarAxes.PolarTransform() inverted.__doc__ = Transform.inverted.__doc__ class ThetaFormatter(Formatter): """ Used to format the *theta* tick labels. Converts the native unit of radians into degrees and adds a degree symbol. """ def __call__(self, x, pos=None): # \u00b0 : degree symbol if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: return r"$%0.0f^\circ$" % ((x / np.pi) * 180.0) else: # we use unicode, rather than mathtext with \circ, so # that it will work correctly with any arbitrary font # (assuming it has a degree sign), whereas $5\circ$ # will only work correctly with one of the supported # math fonts (Computer Modern and STIX) return u"%0.0f\u00b0" % ((x / np.pi) * 180.0) class RadialLocator(Locator): """ Used to locate radius ticks. Ensures that all ticks are strictly positive. For all other tasks, it delegates to the base :class:`~matplotlib.ticker.Locator` (which may be different depending on the scale of the *r*-axis. """ def __init__(self, base): self.base = base def __call__(self): ticks = self.base() return [x for x in ticks if x > 0] def autoscale(self): return self.base.autoscale() def pan(self, numsteps): return self.base.pan(numsteps) def zoom(self, direction): return self.base.zoom(direction) def refresh(self): return self.base.refresh() def view_limits(self, vmin, vmax): vmin, vmax = self.base.view_limits(vmin, vmax) return 0, vmax def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. The following optional kwargs are supported: - *resolution*: The number of points of interpolation between each pair of data points. Set to 1 to disable interpolation. """ self._rpad = 0.05 self.resolution = kwargs.pop('resolution', None) if self.resolution not in (None, 1): warnings.warn( """The resolution kwarg to Polar plots is now ignored. If you need to interpolate data points, consider running cbook.simple_linear_interpolation on the data before passing to matplotlib.""") Axes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() __init__.__doc__ = Axes.__init__.__doc__ def cla(self): Axes.cla(self) self.title.set_y(1.05) self.xaxis.set_major_formatter(self.ThetaFormatter()) self.xaxis.isDefault_majfmt = True angles = np.arange(0.0, 360.0, 45.0) self.set_thetagrids(angles) self.yaxis.set_major_locator( self.RadialLocator(self.yaxis.get_major_locator())) self.grid(rcParams['polaraxes.grid']) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? def _init_axis(self): "move this out of __init__ because non-separable axes don't use it" self.xaxis = maxis.XAxis(self) self.yaxis = maxis.YAxis(self) # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla() # results in weird artifacts. Therefore we disable this for # now. # self.spines['polar'].register_axis(self.yaxis) self._update_transScale() def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) # data. This one is aware of rmin self.transProjection = self.PolarTransform(self) # This one is not aware of rmin self.transPureProjection = self.PolarTransform() # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = self.transScale + self.transProjection + \ (self.transProjectionAffine + self.transAxes) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 1.0 at # the edge of the axis circle. self._xaxis_transform = (self.transPureProjection + self.PolarAffine( IdentityTransform(), Bbox.unit()) + self.transAxes) # The theta labels are moved from radius == 0.0 to radius == 1.1 self._theta_label1_position = Affine2D().translate(0.0, 1.1) self._xaxis_text1_transform = (self._theta_label1_position + self._xaxis_transform) self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1) self._xaxis_text2_transform = (self._theta_label2_position + self._xaxis_transform) # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to # 2pi. self._yaxis_transform = (Affine2D().scale(np.pi * 2.0, 1.0) + self.transData) # The r-axis labels are put at an angle and padded in the r-direction self._r_label1_position = ScaledTranslation( 22.5, self._rpad, blended_transform_factory(Affine2D(), BboxTransformToMaxOnly(self.viewLim))) self._yaxis_text1_transform = (self._r_label1_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform) self._r_label2_position = ScaledTranslation( 22.5, -self._rpad, blended_transform_factory(Affine2D(), BboxTransformToMaxOnly(self.viewLim))) self._yaxis_text2_transform = (self._r_label2_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform) def get_xaxis_transform(self, which='grid'): assert which in ['tick1', 'tick2', 'grid'] return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return self._xaxis_text1_transform, 'center', 'center' def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'center', 'center' def get_yaxis_transform(self, which='grid'): assert which in ['tick1', 'tick2', 'grid'] return self._yaxis_transform def get_yaxis_text1_transform(self, pad): return self._yaxis_text1_transform, 'center', 'center' def get_yaxis_text2_transform(self, pad): return self._yaxis_text2_transform, 'center', 'center' def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): return {'polar': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)} def set_rmax(self, rmax): self.viewLim.y1 = rmax def get_rmax(self): return self.viewLim.ymax def set_rmin(self, rmin): self.viewLim.y0 = rmin def get_rmin(self): return self.viewLim.ymin def set_rlim(self, *args, **kwargs): if 'rmin' in kwargs: kwargs['ymin'] = kwargs.pop('rmin') if 'rmax' in kwargs: kwargs['ymax'] = kwargs.pop('rmax') return self.set_ylim(*args, **kwargs) def set_yscale(self, *args, **kwargs): Axes.set_yscale(self, *args, **kwargs) self.yaxis.set_major_locator( self.RadialLocator(self.yaxis.get_major_locator())) set_rscale = Axes.set_yscale set_rticks = Axes.set_yticks @docstring.dedent_interpd def set_thetagrids(self, angles, labels=None, frac=None, fmt=None, **kwargs): """ Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not None, is a ``len(angles)`` list of strings of the labels to use at each angle. If *labels* is None, the labels will be ``fmt %% angle`` *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). Eg. 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ angles = np.asarray(angles, np.float_) self.set_xticks(angles * (np.pi / 180.0)) if labels is not None: self.set_xticklabels(labels) elif fmt is not None: self.xaxis.set_major_formatter(FormatStrFormatter(fmt)) if frac is not None: self._theta_label1_position.clear().translate(0.0, frac) self._theta_label2_position.clear().translate(0.0, 1.0 / frac) for t in self.xaxis.get_ticklabels(): t.update(kwargs) return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels() @docstring.dedent_interpd def set_rgrids(self, radii, labels=None, angle=None, rpad=None, fmt=None, **kwargs): """ Set the radial locations and labels of the *r* grids. The labels will appear at radial distances *radii* at the given *angle* in degrees. *labels*, if not None, is a ``len(radii)`` list of strings of the labels to use at each radius. If *labels* is None, the built-in formatter will be used. *rpad* is a fraction of the max of *radii* which will pad each of the radial labels in the radial direction. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ radii = np.asarray(radii) rmin = radii.min() if rmin <= 0: raise ValueError('radial grids must be strictly positive') self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) elif fmt is not None: self.yaxis.set_major_formatter(FormatStrFormatter(fmt)) if angle is None: angle = self._r_label1_position.to_values()[4] if rpad is not None: self._rpad = rpad self._r_label1_position._t = (angle, self._rpad) self._r_label1_position.invalidate() self._r_label2_position._t = (angle, -self._rpad) self._r_label2_position.invalidate() for t in self.yaxis.get_ticklabels(): t.update(kwargs) return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels() def set_xscale(self, scale, *args, **kwargs): if scale != 'linear': raise NotImplementedError( "You can not set the xscale on a polar plot.") def set_xlim(self, *args, **kargs): # The xlim is fixed, no matter what you do self.viewLim.intervalx = (0.0, np.pi * 2.0) def format_coord(self, theta, r): """ Return a format string formatting the coordinate using Unicode characters. """ theta /= math.pi # \u03b8: lower-case theta # \u03c0: lower-case pi # \u00b0: degree symbol return u'\u03b8=%0.3f\u03c0 (%0.3f\u00b0), r=%0.3f' % (theta, theta * 180.0, r) def get_data_ratio(self): ''' Return the aspect ratio of the data itself. For a polar plot, this should always be 1.0 ''' return 1.0 ### Interactive panning def can_zoom(self): """ Return True if this axes support the zoom box """ return False def start_pan(self, x, y, button): angle = self._r_label1_position.to_values()[4] / 180.0 * np.pi mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if t >= angle - epsilon and t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = cbook.Bunch( rmax=self.get_rmax(), trans=self.transData.frozen(), trans_inverse=self.transData.inverted().frozen(), r_label_angle=self._r_label1_position.to_values()[4], x=x, y=y, mode=mode) def end_pan(self): del self._pan_start def drag_pan(self, button, key, x, y): p = self._pan_start if p.mode == 'drag_r_labels': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) # Deal with theta dt0 = t - startt dt1 = startt - t if abs(dt1) < abs(dt0): dt = abs(dt1) * sign(dt0) * -1.0 else: dt = dt0 * -1.0 dt = (dt / np.pi) * 180.0 rpad = self._rpad self._r_label1_position._t = (p.r_label_angle - dt, rpad) self._r_label1_position.invalidate() self._r_label2_position._t = (p.r_label_angle - dt, -rpad) self._r_label2_position.invalidate() elif p.mode == 'zoom': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) dr = r - startr # Deal with r scale = r / startr self.set_rmax(p.rmax / scale)
def generate_hydrograph(self, wxdset=None, wldset=None): wxdset = self.wxdset if wxdset is None else wxdset wldset = self.wldset if wldset is None else wldset # Reinit the figure. self.clf() self.set_size_inches(self.fwidth, self.fheight, forward=True) self.setup_figure_frame() # Assign Weather Data. if self.wxdset is None: self.name_meteo = '' self.TIMEmeteo = np.array([]) self.TMAX = np.array([]) self.PTOT = np.array([]) self.RAIN = np.array([]) else: self.name_meteo = wxdset.metadata['Station Name'] self.TIMEmeteo = datetimeindex_to_xldates(wxdset.data.index) self.TMAX = wxdset.data['Tmax'].values self.PTOT = wxdset.data['Ptot'].values self.RAIN = wxdset.data['Rain'].values # Resample Data in Bins : self.resample_bin() # -------------------------------------------------- AXES CREATION ---- # ---- Time (host) ---- # Also holds the gridlines. self.ax1 = self.add_axes([0, 0, 1, 1], frameon=False) self.ax1.set_zorder(100) # ---- Frame ---- # Only used to display the frame so it is always on top. self.ax0 = self.add_axes(self.ax1.get_position(), frameon=True) self.ax0.patch.set_visible(False) self.ax0.set_zorder(self.ax1.get_zorder() + 200) self.ax0.tick_params(bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) # ---- Water Levels ---- self.ax2 = self.add_axes(self.ax1.get_position(), frameon=False, label='axes2', sharex=self.ax1) self.ax2.set_zorder(self.ax1.get_zorder() + 100) self.ax2.yaxis.set_ticks_position('left') self.ax2.yaxis.set_label_position('left') self.ax2.tick_params(axis='y', direction='out', labelsize=10) # ---- Precipitation ---- self.ax3 = self.add_axes(self.ax1.get_position(), frameon=False, label='axes3', sharex=self.ax1) self.ax3.set_zorder(self.ax1.get_zorder() + 150) self.ax3.set_navigate(False) # ---- Air Temperature ---- self.ax4 = self.add_axes(self.ax1.get_position(), frameon=False, label='axes4', sharex=self.ax1) self.ax4.set_zorder(self.ax1.get_zorder() + 150) self.ax4.set_navigate(False) self.ax4.set_axisbelow(True) self.ax4.tick_params(bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) if self.meteo_on is False: self.ax3.set_visible(False) self.ax4.set_visible(False) # ---- Bottom Graph Grid ---- self.axLow = self.add_axes(self.ax1.get_position(), frameon=False, label='axLow', sharex=self.ax1) self.axLow.patch.set_visible(False) self.axLow.set_zorder(self.ax2.get_zorder() - 50) self.axLow.tick_params(bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) self.setup_waterlvl_scale() # -------------------------------------------------- Remove Spines ---- for axe in self.axes[2:]: for loc in axe.spines: axe.spines[loc].set_visible(False) # ------------------------------------------------- Update margins ---- self.bottom_margin = 0.75 self.set_margins() # set margins for all the axes # --------------------------------------------------- FIGURE TITLE ---- # Calculate horizontal distance between weather station and # observation well. if self.wxdset is not None: self.dist = calc_dist_from_coord( wldset['Latitude'], wldset['Longitude'], wxdset.metadata['Latitude'], wxdset.metadata['Longitude']) else: self.dist = 0 # Weather Station name and distance to the well self.text1 = self.ax0.text(0, 1, '', va='bottom', ha='left', rotation=0, fontsize=10) # Well Name self.figTitle = self.ax0.text(0, 1, '', fontsize=18, ha='left', va='bottom') self.draw_figure_title() # ----------------------------------------------------------- TIME ---- self.xlabels = [] self.set_time_scale() self.ax1.xaxis.set_ticklabels([]) self.ax1.xaxis.set_ticks_position('bottom') self.ax1.tick_params(axis='x', direction='out') self.ax1.tick_params(top=False, left=False, right=False, labeltop=False, labelleft=False, labelright=False) self.set_gridLines() # ---- Init water level artists # Continuous Line Datalogger self.l1_ax2, = self.ax2.plot( [], [], '-', zorder=10, lw=1, color=self.colorsDB.rgb['WL solid']) # Data Point Datalogger self.l2_ax2, = self.ax2.plot( [], [], '.', color=self.colorsDB.rgb['WL data'], markersize=5) # Manual Mesures self.h_WLmes, = self.ax2.plot( [], [], 'o', zorder=15, label='Manual measures', markerfacecolor='none', markersize=5, markeredgewidth=1.5, mec=self.colorsDB.rgb['WL obs']) # Predicted Recession Curves self._mrc_plt, = self.ax2.plot( [], [], color='red', lw=1.5, dashes=[5, 3], zorder=100, alpha=0.85) # Predicted GLUE water levels self.glue_plt, = self.ax2.plot([], []) self.draw_waterlvl() self.draw_glue_wl() self.draw_mrc_wl() # ---- Init weather artists # ---- PRECIPITATION ----- self.ax3.yaxis.set_ticks_position('right') self.ax3.yaxis.set_label_position('right') self.ax3.tick_params(axis='y', direction='out', labelsize=10) self.PTOT_bar, = self.ax3.plot([], []) self.RAIN_bar, = self.ax3.plot([], []) self.baseline, = self.ax3.plot( [self.TIMEmin, self.TIMEmax], [0, 0], 'k') # ---- AIR TEMPERATURE ----- TEMPmin = -40 TEMPscale = 20 TEMPmax = 40 self.ax4.axis(ymin=TEMPmin, ymax=TEMPmax) yticks_position = np.array([TEMPmin, 0, TEMPmax]) yticks_position = np.arange( TEMPmin, TEMPmax + TEMPscale / 2, TEMPscale) self.ax4.set_yticks(yticks_position) self.ax4.yaxis.set_ticks_position('left') self.ax4.tick_params(axis='y', direction='out', labelsize=10) self.ax4.yaxis.set_label_position('left') self.ax4.set_yticks([-20, 20], minor=True) self.ax4.tick_params(axis='y', which='minor', length=0) self.ax4.xaxis.set_ticklabels([], minor=True) self.l1_ax4, = self.ax4.plot([], []) # fill shape self.l2_ax4, = self.ax4.plot( [], [], color='black', lw=1) # contour line # ---- MISSING VALUES MARKERS # Precipitation. vshift = 5 / 72 offset = ScaledTranslation(0, vshift, self.dpi_scale_trans) if self.wxdset is not None: t1 = pd.DataFrame(self.wxdset.missing_value_indexes['Ptot'], index=self.wxdset.missing_value_indexes['Ptot'], columns=['datetime']) t2 = pd.DataFrame(self.wxdset.missing_value_indexes['Ptot'] + pd.Timedelta('1 days'), self.wxdset.missing_value_indexes['Ptot'] + pd.Timedelta('1 days'), columns=['datetime']) time = datetimeindex_to_xldates(pd.DatetimeIndex( pd.concat([t1, t2], axis=0) .drop_duplicates() .resample('1D') .asfreq() ['datetime'] )) y = np.ones(len(time)) * self.ax4.get_ylim()[0] else: time, y = [], [] self.lmiss_ax4, = self.ax4.plot( time, y, ls='-', solid_capstyle='projecting', lw=1, c='red', transform=self.ax4.transData + offset) # Air Temperature. offset = ScaledTranslation(0, -vshift, self.dpi_scale_trans) if self.wxdset is not None: t1 = pd.DataFrame(self.wxdset.missing_value_indexes['Tmax'], index=self.wxdset.missing_value_indexes['Tmax'], columns=['datetime']) t2 = pd.DataFrame(self.wxdset.missing_value_indexes['Tmax'] + pd.Timedelta('1 days'), self.wxdset.missing_value_indexes['Tmax'] + pd.Timedelta('1 days'), columns=['datetime']) time = datetimeindex_to_xldates(pd.DatetimeIndex( pd.concat([t1, t2], axis=0) .drop_duplicates() .resample('1D') .asfreq() ['datetime'] )) y = np.ones(len(time)) * self.ax4.get_ylim()[1] else: time, y = [], [] self.ax4.plot(time, y, ls='-', solid_capstyle='projecting', lw=1., c='red', transform=self.ax4.transData + offset) self.draw_weather() self.draw_ylabels() self.setup_legend() self.__isHydrographExists = True
def fnoise_plots(mode,ifeed): filelist = np.loadtxt(sys.argv[1],dtype=str) obsid = np.array([int(f.split('-')[1]) for f in filelist]) filelist = filelist[np.argsort(obsid)] obsid = np.sort(obsid) fnoise = np.zeros(filelist.size) enoise = np.zeros(filelist.size) feed = None isfg4 = np.zeros(filelist.size,dtype=bool) dist = np.zeros(filelist.size) fnoise_power = np.zeros((filelist.size,64*4)) alphas = np.zeros((filelist.size,64*4)) for ifile, filename in enumerate(filelist): try: data = h5py.File(filename,'r') except OSError: print('{} cannot be opened (Resource unavailable)'.format(filename)) fnoise[ifile] = np.nan if mode.lower() in data['level1/comap'].attrs['source'].decode('utf-8').lower(): isfg4[ifile] = True try: fits = data['level2/fnoise_fits'][ifeed,:,:,:] fnoise[ifile] = np.median(fits[:,1]) enoise[ifile] = np.sqrt(np.median(np.abs(fits[:,1]-fnoise[ifile])**2))*1.4826 ps = data['level2/powerspectra'][ifeed,:,:,:] rms = data['level2/wnoise_auto'][ifeed,:,:,:] nu = data['level2/freqspectra'][ifeed,:,:,:] freq = data['level1/spectrometer/frequency'][...] bw = 16 freq = np.mean(np.reshape(freq, (freq.shape[0],freq.shape[1]//bw, bw)),axis=-1).flatten() sfreq = np.argsort(freq) fnoise_power[ifile,:] = (rms[:,:,0]**2 * (1/fits[:,:,0])**fits[:,:,1]).flatten()[sfreq] alphas[ifile,:] = (fits[:,:,1]).flatten()[sfreq] #print(nu.shape,ps.shape, rms.shape, fits.shape) #pyplot.plot(freq[sfreq],fnoise_power[ifile,:]) except IOError: print('{} not processed'.format(filename.split('/')[-1])) fnoise[ifile] = np.nan if isinstance(feed, type(None)): feed = data['level1/spectrometer/feeds'][ifeed] # Calculate sun distance mjd = data['level1/spectrometer/MJD'][0:1] lon=-118.2941 lat=37.2314 ra_sun, dec_sun, raddist = Coordinates.getPlanetPosition('SUN', lon, lat, mjd) az_sun, el_sun = Coordinates.e2h(ra_sun, dec_sun, mjd, lon, lat) ra = data['level1/spectrometer/pixel_pointing/pixel_ra'][0,0:1] dec = data['level1/spectrometer/pixel_pointing/pixel_dec'][0,0:1] dist[ifile] = el_sun[0]#angular_seperation(ra_sun, ra, dec_sun, dec) data.close() # Plot obs ID vs fnoise power pyplot.imshow(np.log10(fnoise_power*1e3),aspect='auto',origin='lower', extent=[np.min(freq),np.max(freq),-.5,fnoise_power.shape[0]-0.5]) pyplot.yticks(np.arange(fnoise_power.shape[0])-0.5, obsid, rotation=0, ha='right',va='center',size=10) ax = pyplot.gca() fig = pyplot.gcf() offset = ScaledTranslation(-0.08,0.02,fig.transFigure) for label in ax.yaxis.get_majorticklabels(): label.set_transform(label.get_transform() + offset) pyplot.grid() pyplot.xlabel('Frequency (GHz)') pyplot.ylabel('obs ID') pyplot.colorbar(label=r'$\mathrm{log}_{10}$(mK)') pyplot.title('Feed {}'.format(feed)) pyplot.savefig('Plots/fnoise_gfields_Feed{}.png'.format(feed),bbox_inches='tight') pyplot.clf() # Plot obs ID vs fnoise power pyplot.imshow(alphas,aspect='auto',origin='lower',vmin=-1.5,vmax=-0.9, extent=[np.min(freq),np.max(freq),-.5,fnoise_power.shape[0]-0.5]) pyplot.yticks(np.arange(fnoise_power.shape[0])-0.5, obsid, rotation=0, ha='right',va='center',size=10) ax = pyplot.gca() fig = pyplot.gcf() for label in ax.yaxis.get_majorticklabels(): label.set_transform(label.get_transform() + offset) pyplot.grid() pyplot.xlabel('Frequency (GHz)') pyplot.ylabel('obs ID') pyplot.colorbar(label=r'$\alpha$') pyplot.title('Feed {}'.format(feed)) pyplot.savefig('Plots/alphas_gfields_Feed{}.png'.format(feed),bbox_inches='tight') pyplot.clf()
def plotGenomeTracks(tracks, chromosome, coordStart, coordEnd, style='ggplot', outpath=None, figsize=None): # TODO Refactor into separate functions and classes if figsize is None: figsize = (13., 1. * len(tracks)) def coordFmt(t): if t >= 1000000: return '%.3f Mb' % (t / 1000000.) if t >= 1000: return '%.3f kb' % (t / 1000.) return '%.3f bp' % t try: import matplotlib.pyplot as plt import base64 from io import BytesIO from IPython.core.display import display, HTML from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle, FancyBboxPatch, Polygon from matplotlib.lines import Line2D from matplotlib.transforms import ScaledTranslation import struct with plt.style.context(style): fig, ax = plt.subplots(1, figsize=figsize) # Set up axes plt.yticks(range(len(tracks))) ax.set_xlim(coordStart, coordEnd) ax.set_ylim(0, len(tracks)) ticks = ax.get_xticks() ax.set_xticklabels([coordFmt(t) for t in ticks], fontsize=12) ax.set_yticklabels([]) setYA = [] setYB = [] width = coordEnd - coordStart y = 0. for rs in tracks: yA = y if isinstance(rs, genome): y += 3. elif isinstance(rs, curves): y += 3. if rs.thresholdValue is not None: y += 1. else: y += 1. setYA.append(yA) setYB.append(y) plt.text(coordStart - width * 0.015, (y + yA) / 2. + 0.05, rs.name, verticalalignment='top', horizontalalignment='right', color=ax.yaxis.label.get_color(), fontsize=15, rotation=45, clip_on=False) ax.set_yticks([0.] + setYB) ax.yaxis.set_label_coords(-0.3, 1.5) plt.setp(ax.get_yticklabels(), rotation=45, ha="right", rotation_mode="anchor") plt.tick_params(axis='y', which='both', left=False, right=False) # Shift y axis labels dx = -0.1 dy = 0.2 offset = ScaledTranslation(dx, dy, fig.dpi_scale_trans) for label in ax.yaxis.get_majorticklabels(): label.set_transform(label.get_transform() + offset) # Iterate over tracks rmargin = 0.2 for rsi, ((yA, yB), rs) in enumerate(zip(zip(setYA, setYB), tracks)): # Special treatment of gene annotations, with plotting of genes with exons, CDS and names height = yB - yA colorRaw = plt.rcParams['axes.prop_cycle'].by_key()['color'][ rsi % len(plt.rcParams['axes.prop_cycle'].by_key()['color'])] color = [ v / 255. for v in struct.unpack('BBB', bytes.fromhex(colorRaw[1:])) ] def drawRoundBox(start, end, y, height, fc, ec, rlabel=None, clip_on=True): w = end - start + 1 rs = min(w * 0.5 * width * 0.00001, 500. * width * 0.00001) patch = FancyBboxPatch( (start, y), w, height, boxstyle="round,rounding_size=" + str(rs), mutation_aspect=2. * max(setYB) / width, fc=fc, ec=ec, clip_on=clip_on) ax.add_patch(patch) if rlabel is not None: plt.text(end + width * 0.015, y + height * .5, rlabel, verticalalignment='center', horizontalalignment='left', color=ax.yaxis.label.get_color(), fontsize=10, clip_on=False) return patch def drawBox(start, end, y, height, fc, ec, rlabel=None, clip_on=True): w = end - start + 1 rs = min(w * width * 0.00001, 500. * width * 0.00001) patch = FancyBboxPatch( (start, y), w, height, boxstyle="square", mutation_aspect=2. * max(setYB) / width, fc=fc, ec=ec, clip_on=clip_on) ax.add_patch(patch) if rlabel is not None: plt.text(end + width * 0.015, y + height * .5, rlabel, verticalalignment='center', horizontalalignment='left', color=ax.yaxis.label.get_color(), fontsize=10, clip_on=False) return patch if isinstance(rs, genome): cgenes = [ g for g in rs.genes if g.region.seq == chromosome\ and g.region.end >= coordStart\ and g.region.start <= coordEnd ] cy = height / 2. geneheight = 1. - 2. * rmargin colBody = [0.75, 0.75, 0.75] colExons = [0.45, 0.45, 0.45] colCDS = [0.1, 0.1, 0.1] colBorder = [0.1, 0.1, 0.1, 1.] colInvisible = [0., 0., 0., 0.] # Legend: Gene body def drawGeneBody(start, end, y, height, rlabel=None, clip_on=True): return drawRoundBox(start=start, end=end, y=y, height=height, fc=colBody + [0.4], ec=colInvisible, rlabel=rlabel, clip_on=clip_on) def drawGeneOutline(start, end, y, height, clip_on=True): drawRoundBox(start=start, end=end, y=y, height=height, fc=colInvisible, ec=colBorder, clip_on=clip_on) drawGeneBody(start=coordEnd + width * 0.01, end=coordEnd + width * 0.01 + 3. * 0.006 * width, y=yB - 0.1 - geneheight, height=geneheight, rlabel='Gene body', clip_on=False) drawGeneOutline(start=coordEnd + width * 0.01, end=coordEnd + width * 0.01 + 3. * 0.006 * width, y=yB - 0.1 - geneheight, height=geneheight, clip_on=False) # Legend: Gene exon def drawGeneExon(start, end, y, height, rlabel=None, clip_on=True): drawBox(start=start, end=end, y=y, height=height, fc=colExons + [1.], ec=colInvisible, rlabel=rlabel, clip_on=clip_on) drawGeneExon(start=coordEnd + width * 0.01, end=coordEnd + width * 0.01 + 3. * 0.006 * width, y=yB - 0.1 - geneheight - 0.1 - geneheight, height=geneheight, rlabel='Exon', clip_on=False) #drawGeneOutline(start = coordEnd + width*0.01, end = coordEnd + width*0.01 + 3. * 0.006 * width, y = yB - 0.1 - geneheight - 0.1 - geneheight, height = geneheight, clip_on = False) # Legend: Gene CDS def drawGeneCDS(start, end, y, height, rlabel=None, clip_on=True): drawBox(start=start, end=end, y=y, height=height, fc=colCDS + [1.], ec=colInvisible, rlabel=rlabel, clip_on=clip_on) drawGeneCDS( start=coordEnd + width * 0.01, end=coordEnd + width * 0.01 + 3. * 0.006 * width, y=yB - 0.1 - geneheight - 0.1 - geneheight - 0.1 - geneheight, height=geneheight, rlabel='CDS', clip_on=False) #drawGeneOutline(start = coordEnd + width*0.01, end = coordEnd + width*0.01 + 3. * 0.006 * width, y = yB - 0.1 - geneheight - 0.1 - geneheight - 0.1 - geneheight, height = geneheight, clip_on = False) # for strand in [False, True]: gh = 0.02 exonh = 0.2 ccy = yA + (cy + 0.5 if strand else cy - 0.5) for g in cgenes: if g.region.strand != strand: continue # Gene body drawGeneBody(start=g.region.start, end=g.region.end, y=ccy - geneheight * .5, height=geneheight) # Exons for r in g.exons: drawGeneExon(start=r.start, end=r.end, y=ccy - geneheight * .5, height=geneheight) # CDS for r in g.CDS: drawGeneCDS(start=r.start, end=r.end, y=ccy - geneheight * .5, height=geneheight) # drawGeneOutline(start=g.region.start, end=g.region.end, y=ccy - geneheight * .5, height=geneheight) for g in cgenes: if g.region.strand == strand: center = (g.region.start + g.region.end) / 2. if center <= coordStart or center >= coordEnd: continue ax.text(center, ccy + (0.65 if strand else -0.65), g.name, horizontalalignment='center', verticalalignment='center') continue # Special handling of curves elif isinstance(rs, curves): ccurve = next((c for c in rs if c.seq == chromosome), None) if ccurve == None: continue # Rasterize - logic required depends on curve type if isinstance(ccurve, fixedStepCurve): iA = max(int((coordStart - ccurve.span) / ccurve.step), 0) iB = max( min(int((coordEnd) / ccurve.step), len(ccurve) - 1), 0) span = ccurve.span step = ccurve.step vals = ccurve[iA:iB + 1] # res = 2048 srcXA = iA * ccurve.step #coordStart srcXB = iB * ccurve.step #coordEnd scale = res / (srcXB - srcXA) ret = [None for _ in range(res)] for i, v in enumerate(vals): dstXA = int( min( max( i * ccurve.step * res / ((iB - iA) * ccurve.step), 0), res - 1)) dstXB = int( min( max( res * (i + ccurve.span / ccurve.step) / (iB - iA), 0), res - 1)) for x in range(dstXA, dstXB + 1): Q = (ccurve.step * (iA + (iB - iA) * float(x) / res), v) if ret[x] is None or Q > ret[x]: ret[x] = Q raster = [v for v in ret if v is not None] elif isinstance(ccurve, variableStepCurve): vals = [ v for v in ccurve if v.start + v.span >= coordStart and v.start <= coordEnd ] # res = 2048 srcXA = coordStart srcXB = coordEnd scale = res / (srcXB - srcXA) ret = [None for _ in range(res)] for v in vals: dstXA = int( min(max((v.start - srcXA) * scale, 0), res - 1)) dstXB = int( min(max((v.start + v.span - srcXA) * scale, 0), res - 1)) for x in range(dstXA, dstXB + 1): ret[x] = (srcXA + (float(x) / scale), v.value) raster = [v for v in ret if v is not None] # Plot curve vBase = 0. vMin = min(y for x, y in raster) vMax = max(y for x, y in raster) yBottom = min(vBase, vMin) yTop = vMax cheight = height predHeight = 1. def V2Y(v): return yA + rmargin + ((v + vBase - yBottom) * vScale) if rs.thresholdValue is not None: yBottom = min(yBottom, rs.thresholdValue) yTop = max(yTop, rs.thresholdValue) cheight -= predHeight vScale = (cheight - rmargin * 2.) / (yTop - yBottom) polypts = [] polypts += [(x, V2Y(max(y, vBase))) for x, y in raster] polypts += reversed([(x, V2Y(min(y, vBase))) for x, y in raster]) poly = Polygon(polypts, fc=color[:3] + [0.4], ec=colInvisible) #ec = [ c*0.5 for c in color[:3] ] + [1.]) ax.add_patch(poly) ax.add_line( Line2D([x for x, y in raster], [V2Y(y) for x, y in raster], linewidth=0.8, color=[c * 0.75 for c in color[:3]] + [0.75])) #color = color)) # Legend lyA = V2Y(vMin) lyB = V2Y(vMax) ax.add_patch( Rectangle((coordEnd, lyA), 1. * 0.006 * width, lyB - lyA, fc=(0.2, 0.2, 0.2, 1.), ec=colInvisible, clip_on=False)) tticks = [(vMax, str(vMax)), (vMin, str(vMin))] if rs.thresholdValue is not None: tticks.append( (rs.thresholdValue, str(rs.thresholdValue) + ' (threshold)')) if vMin < 0. and vMax > 0.: tticks.append((0.0, str(0.0))) tticks = sorted(tticks, key=lambda p: p[0]) for v, n in tticks: ly = V2Y(v) ax.add_line( Line2D([ coordEnd + 0. * 0.006 * width, coordEnd + 2. * 0.006 * width ], [ly, ly], color=(0.2, 0.2, 0.2, 1.), linewidth=1., clip_on=False)) plt.text(coordEnd + 3. * 0.006 * width, ly, n, verticalalignment='center', horizontalalignment='left', color=ax.yaxis.label.get_color(), fontsize=8, clip_on=False) # Thresholded if rs.thresholdValue is not None: tthr = V2Y(rs.thresholdValue) ax.plot([coordStart, coordEnd], [tthr, tthr], linestyle='-', color='grey', label='Expected at random') frs = rs.regions().filter('', lambda r: r.seq == chromosome\ and r.end >= coordStart\ and r.start <= coordEnd) for r in frs: drawRoundBox(start=r.start, end=r.end, y=yB - predHeight + rmargin, height=predHeight - 2 * rmargin, fc=color[:3] + [0.4], ec=[c * 0.5 for c in color[:3]] + [1.]) # Legend drawRoundBox(start=coordEnd + width * 0.01, end=coordEnd + width * 0.01 + 3. * 0.006 * width, y=yB - 0.1 - geneheight, height=geneheight, fc=color[:3] + [0.4], ec=[c * 0.5 for c in color[:3]] + [1.], rlabel='Thresholded', clip_on=False) continue # Simpler handling of region sets frs = rs.filter('', lambda r: r.seq == chromosome\ and r.end >= coordStart\ and r.start <= coordEnd) for r in frs: drawRoundBox(start=r.start, end=r.end, y=yA + rmargin, height=height - 2 * rmargin, fc=color[:3] + [0.4], ec=[c * 0.5 for c in color[:3]] + [1.]) # plt.xlabel('Chromosome ' + chromosome, fontsize=18) fig.tight_layout() if outpath is None: bio = BytesIO() fig.savefig(bio, format='png') plt.close('all') encoded = base64.b64encode(bio.getvalue()).decode('utf-8') html = '<img src=\'data:image/png;base64,%s\'>' % encoded display(HTML(html)) else: fig.savefig(outpath) plt.close('all') # except ImportError as err: raise err
def __init__(self, lang='English'): lang = lang if lang.lower() in FigureLabels.LANGUAGES else 'English' self.__figlang = lang self.__figlabels = FigureLabels(lang) self.normals = None fw, fh = 8.5, 5. fig = MplFigure(figsize=(fw, fh), facecolor='white') super(FigWeatherNormals, self).__init__(fig) # Define the margins. left_margin = 1 / fw right_margin = 1 / fw bottom_margin = 0.7 / fh top_margin = 0.1 / fh # ---- Yearly Avg Labels # The yearly yearly averages for the mean air temperature and # the total precipitation are displayed in <ax3>, which is placed on # top of the axes that display the data (<ax0> and <ax1>). ax3 = fig.add_axes([0, 0, 1, 1], zorder=1, label='axe3') ax3.patch.set_visible(False) ax3.spines['bottom'].set_visible(False) ax3.tick_params(axis='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labeltop=False, labelleft=False, labelright=False) # Mean Annual Air Temperature : # Places first label at the top left corner of <ax3> with a horizontal # padding of 5 points and downward padding of 3 points. dx, dy = 5 / 72., -3 / 72. padding = ScaledTranslation(dx, dy, fig.dpi_scale_trans) transform = ax3.transAxes + padding ax3.text(0., 1., 'Mean Annual Air Temperature', fontsize=13, va='top', transform=transform) # Mean Annual Precipitation : # Get the bounding box of the first label. renderer = self.get_renderer() bbox = ax3.texts[0].get_window_extent(renderer) bbox = bbox.transformed(ax3.transAxes.inverted()) # Places second label below the first label with a horizontal # padding of 5 points and downward padding of 3 points. ax3.text(0., bbox.y0, 'Mean Annual Precipitation', fontsize=13, va='top', transform=transform) bbox = ax3.texts[1].get_window_extent(renderer) bbox = bbox.transformed(fig.transFigure.inverted()) # Update geometry : # Updates the geometry and position of <ax3> to accomodate the text. x0 = left_margin axw = 1 - (left_margin + right_margin) axh = 1 - bbox.y0 - (dy / fw) y0 = 1 - axh - top_margin ax3.set_position([x0, y0, axw, axh]) # ---- Data Axes axh = y0 - bottom_margin y0 = y0 - axh # Precipitation : ax0 = fig.add_axes([x0, y0, axw, axh], zorder=1, label='axe0') ax0.patch.set_visible(False) ax0.spines['top'].set_visible(False) ax0.set_axisbelow(True) # Air Temperature : ax1 = fig.add_axes(ax0.get_position(), frameon=False, zorder=5, sharex=ax0, label='axe1') # ---- Initialize the Artists # This is only to initiates the artists and to set their parameters # in advance. The plotting of the data is actually done by calling # the <plot_monthly_normals> method. XPOS = np.arange(-0.5, 12.51, 1) XPOS[0] = 0 XPOS[-1] = 12 y = range(len(XPOS)) colors = ['#990000', '#FF0000', '#FF6666'] # Dashed lines for Tmax, Tavg, and Tmin : for i in range(3): ax1.plot(XPOS, y, color=colors[i], ls='--', lw=1.5, zorder=100) # Markers for Tavg : ax1.plot(XPOS[1:-1], y[1:-1], color=colors[1], marker='o', ls='none', ms=6, zorder=100, mec=colors[1], mfc='white', mew=1.5) # ---- Xticks Formatting Xmin0 = 0 Xmax0 = 12.001 # Major ticks ax0.xaxis.set_ticks_position('bottom') ax0.tick_params(axis='x', direction='out') ax0.xaxis.set_ticklabels([]) ax0.set_xticks(np.arange(Xmin0, Xmax0)) ax1.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) # Minor ticks ax0.set_xticks(np.arange(Xmin0 + 0.5, Xmax0 + 0.49, 1), minor=True) ax0.tick_params(axis='x', which='minor', direction='out', length=0, labelsize=13) ax0.xaxis.set_ticklabels(self.fig_labels.month_names, minor=True) # ---- Y-ticks Formatting # Precipitation ax0.yaxis.set_ticks_position('right') ax0.tick_params(axis='y', direction='out', labelsize=13) ax0.tick_params(axis='y', which='minor', direction='out') ax0.yaxis.set_ticklabels([], minor=True) # Air Temperature ax1.yaxis.set_ticks_position('left') ax1.tick_params(axis='y', direction='out', labelsize=13) ax1.tick_params(axis='y', which='minor', direction='out') ax1.yaxis.set_ticklabels([], minor=True) # ---- Grid Parameters # ax0.grid(axis='y', color=[0.5, 0.5, 0.5], linestyle=':', linewidth=1, # dashes=[1, 5]) # ax0.grid(axis='y', color=[0.75, 0.75, 0.75], linestyle='-', # linewidth=0.5) # ---- Limits of the Axes ax0.set_xlim(Xmin0, Xmax0) # ---- Legend self.plot_legend()
import numpy as np import matplotlib.pyplot as plt from matplotlib.transforms import blended_transform_factory, ScaledTranslation fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(1, 1, 1, aspect=1) ax.set_xlim(0, 10) ax.set_xticks(range(11)) ax.set_ylim(0, 5) ax.set_xticks(range(11)) point = 1 / 72 fontsize = 12 dx, dy = 0, -1.5 * fontsize * point offset = ScaledTranslation(dx, dy, fig.dpi_scale_trans) transform = blended_transform_factory(ax.transData, ax.transAxes + offset) for x in range(11): plt.text(x, 0, "↑", transform=transform, ha="center", va="top", fontsize=fontsize) plt.tight_layout() plt.savefig("../../figures/coordinates/transforms-blend.pdf") plt.show()
def transform_non_affine(self, values): x, y = self._get_translation() trans = ScaledTranslation(x, y, self.figure.dpi_scale_trans) return trans.transform(values)
class PolarAxes(Axes): """ A polar graph projection, where the input dimensions are *theta*, *r*. Theta starts pointing east and goes anti-clockwise. """ name = 'polar' def __init__(self, *args, **kwargs): """ Create a new Polar Axes for a polar plot. The following optional kwargs are supported: - *resolution*: The number of points of interpolation between each pair of data points. Set to 1 to disable interpolation. """ self.resolution = kwargs.pop('resolution', 1) self._default_theta_offset = kwargs.pop('theta_offset', 0) self._default_theta_direction = kwargs.pop('theta_direction', 1) self._default_rlabel_position = kwargs.pop('rlabel_position', 22.5) if self.resolution not in (None, 1): warnings.warn( """The resolution kwarg to Polar plots is now ignored. If you need to interpolate data points, consider running cbook.simple_linear_interpolation on the data before passing to matplotlib.""") Axes.__init__(self, *args, **kwargs) self.set_aspect('equal', adjustable='box', anchor='C') self.cla() __init__.__doc__ = Axes.__init__.__doc__ def cla(self): Axes.cla(self) self.title.set_y(1.05) self.xaxis.set_major_formatter(self.ThetaFormatter()) self.xaxis.isDefault_majfmt = True angles = np.arange(0.0, 360.0, 45.0) self.set_thetagrids(angles) self.yaxis.set_major_locator(self.RadialLocator(self.yaxis.get_major_locator())) self.grid(rcParams['polaraxes.grid']) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? self.set_theta_offset(self._default_theta_offset) self.set_theta_direction(self._default_theta_direction) def _init_axis(self): "move this out of __init__ because non-separable axes don't use it" self.xaxis = maxis.XAxis(self) self.yaxis = maxis.YAxis(self) # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla() # results in weird artifacts. Therefore we disable this for # now. # self.spines['polar'].register_axis(self.yaxis) self._update_transScale() def _set_lim_and_transforms(self): self.transAxes = BboxTransformTo(self.bbox) # Transforms the x and y axis separately by a scale factor # It is assumed that this part will have non-linear components self.transScale = TransformWrapper(IdentityTransform()) # A (possibly non-linear) projection on the (already scaled) # data. This one is aware of rmin self.transProjection = self.PolarTransform(self) # This one is not aware of rmin self.transPureProjection = self.PolarTransform(self, use_rmin=False) # An affine transformation on the data, generally to limit the # range of the axes self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim) # The complete data transformation stack -- from data all the # way to display coordinates self.transData = self.transScale + self.transProjection + \ (self.transProjectionAffine + self.transAxes) # This is the transform for theta-axis ticks. It is # equivalent to transData, except it always puts r == 1.0 at # the edge of the axis circle. self._xaxis_transform = ( self.transPureProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes) # The theta labels are moved from radius == 0.0 to radius == 1.1 self._theta_label1_position = Affine2D().translate(0.0, 1.1) self._xaxis_text1_transform = ( self._theta_label1_position + self._xaxis_transform) self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1) self._xaxis_text2_transform = ( self._theta_label2_position + self._xaxis_transform) # This is the transform for r-axis ticks. It scales the theta # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to # 2pi. self._yaxis_transform = ( Affine2D().scale(np.pi * 2.0, 1.0) + self.transData) # The r-axis labels are put at an angle and padded in the r-direction self._r_label_position = ScaledTranslation( self._default_rlabel_position, 0.0, Affine2D()) self._yaxis_text_transform = ( self._r_label_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform ) def get_xaxis_transform(self,which='grid'): if which not in ['tick1','tick2','grid']: msg = "'which' must be one of [ 'tick1' | 'tick2' | 'grid' ]" raise ValueError(msg) return self._xaxis_transform def get_xaxis_text1_transform(self, pad): return self._xaxis_text1_transform, 'center', 'center' def get_xaxis_text2_transform(self, pad): return self._xaxis_text2_transform, 'center', 'center' def get_yaxis_transform(self,which='grid'): if which not in ['tick1','tick2','grid']: msg = "'which' must be on of [ 'tick1' | 'tick2' | 'grid' ]" raise ValueError(msg) return self._yaxis_transform def get_yaxis_text1_transform(self, pad): angle = self.get_rlabel_position() if angle < 90.: return self._yaxis_text_transform, 'bottom', 'left' elif angle < 180.: return self._yaxis_text_transform, 'bottom', 'right' elif angle < 270.: return self._yaxis_text_transform, 'top', 'right' else: return self._yaxis_text_transform, 'top', 'left' def get_yaxis_text2_transform(self, pad): angle = self.get_rlabel_position() if angle < 90.: return self._yaxis_text_transform, 'top', 'right' elif angle < 180.: return self._yaxis_text_transform, 'top', 'left' elif angle < 270.: return self._yaxis_text_transform, 'bottom', 'left' else: return self._yaxis_text_transform, 'bottom', 'right' def _gen_axes_patch(self): return Circle((0.5, 0.5), 0.5) def _gen_axes_spines(self): return {'polar':mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)} def set_rmax(self, rmax): self.viewLim.y1 = rmax def get_rmax(self): return self.viewLim.ymax def set_rmin(self, rmin): self.viewLim.y0 = rmin def get_rmin(self): return self.viewLim.ymin def set_theta_offset(self, offset): """ Set the offset for the location of 0 in radians. """ self._theta_offset = offset def get_theta_offset(self): """ Get the offset for the location of 0 in radians. """ return self._theta_offset def set_theta_zero_location(self, loc): """ Sets the location of theta's zero. (Calls set_theta_offset with the correct value in radians under the hood.) May be one of "N", "NW", "W", "SW", "S", "SE", "E", or "NE". """ mapping = { 'N': np.pi * 0.5, 'NW': np.pi * 0.75, 'W': np.pi, 'SW': np.pi * 1.25, 'S': np.pi * 1.5, 'SE': np.pi * 1.75, 'E': 0, 'NE': np.pi * 0.25 } return self.set_theta_offset(mapping[loc]) def set_theta_direction(self, direction): """ Set the direction in which theta increases. clockwise, -1: Theta increases in the clockwise direction counterclockwise, anticlockwise, 1: Theta increases in the counterclockwise direction """ if direction in ('clockwise',): self._direction = -1 elif direction in ('counterclockwise', 'anticlockwise'): self._direction = 1 elif direction in (1, -1): self._direction = direction else: raise ValueError("direction must be 1, -1, clockwise or counterclockwise") def get_theta_direction(self): """ Get the direction in which theta increases. -1: Theta increases in the clockwise direction 1: Theta increases in the counterclockwise direction """ return self._direction def set_rlim(self, *args, **kwargs): if 'rmin' in kwargs: kwargs['ymin'] = kwargs.pop('rmin') if 'rmax' in kwargs: kwargs['ymax'] = kwargs.pop('rmax') return self.set_ylim(*args, **kwargs) def get_rlabel_position(self): """ Returns ------- float The theta position of the radius labels in degrees. """ return self._r_label_position.to_values()[4] def set_rlabel_position(self, value): """Updates the theta position of the radius labels. Parameters ---------- value : number The angular position of the radius labels in degrees. """ self._r_label_position._t = (value, 0.0) self._r_label_position.invalidate() def set_yscale(self, *args, **kwargs): Axes.set_yscale(self, *args, **kwargs) self.yaxis.set_major_locator( self.RadialLocator(self.yaxis.get_major_locator())) def set_rscale(self, *args, **kwargs): return Axes.set_yscale(self, *args, **kwargs) def set_rticks(self, *args, **kwargs): return Axes.set_yticks(self, *args, **kwargs) @docstring.dedent_interpd def set_thetagrids(self, angles, labels=None, frac=None, fmt=None, **kwargs): """ Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not None, is a ``len(angles)`` list of strings of the labels to use at each angle. If *labels* is None, the labels will be ``fmt %% angle`` *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). e.g., 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data angles = self.convert_yunits(angles) angles = np.asarray(angles, np.float_) self.set_xticks(angles * (np.pi / 180.0)) if labels is not None: self.set_xticklabels(labels) elif fmt is not None: self.xaxis.set_major_formatter(FormatStrFormatter(fmt)) if frac is not None: self._theta_label1_position.clear().translate(0.0, frac) self._theta_label2_position.clear().translate(0.0, 1.0 / frac) for t in self.xaxis.get_ticklabels(): t.update(kwargs) return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels() @docstring.dedent_interpd def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs): """ Set the radial locations and labels of the *r* grids. The labels will appear at radial distances *radii* at the given *angle* in degrees. *labels*, if not None, is a ``len(radii)`` list of strings of the labels to use at each radius. If *labels* is None, the built-in formatter will be used. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data radii = self.convert_xunits(radii) radii = np.asarray(radii) rmin = radii.min() if rmin <= 0: raise ValueError('radial grids must be strictly positive') self.set_yticks(radii) if labels is not None: self.set_yticklabels(labels) elif fmt is not None: self.yaxis.set_major_formatter(FormatStrFormatter(fmt)) if angle is None: angle = self.get_rlabel_position() self.set_rlabel_position(angle) for t in self.yaxis.get_ticklabels(): t.update(kwargs) return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels() def set_xscale(self, scale, *args, **kwargs): if scale != 'linear': raise NotImplementedError("You can not set the xscale on a polar plot.") def set_xlim(self, *args, **kargs): # The xlim is fixed, no matter what you do self.viewLim.intervalx = (0.0, np.pi * 2.0) def format_coord(self, theta, r): """ Return a format string formatting the coordinate using Unicode characters. """ theta /= math.pi # \u03b8: lower-case theta # \u03c0: lower-case pi # \u00b0: degree symbol return '\u03b8=%0.3f\u03c0 (%0.3f\u00b0), r=%0.3f' % (theta, theta * 180.0, r) def get_data_ratio(self): ''' Return the aspect ratio of the data itself. For a polar plot, this should always be 1.0 ''' return 1.0 ### Interactive panning def can_zoom(self): """ Return *True* if this axes supports the zoom box button functionality. Polar axes do not support zoom boxes. """ return False def can_pan(self) : """ Return *True* if this axes supports the pan/zoom button functionality. For polar axes, this is slightly misleading. Both panning and zooming are performed by the same button. Panning is performed in azimuth while zooming is done along the radial. """ return True def start_pan(self, x, y, button): angle = np.deg2rad(self.get_rlabel_position()) mode = '' if button == 1: epsilon = np.pi / 45.0 t, r = self.transData.inverted().transform_point((x, y)) if t >= angle - epsilon and t <= angle + epsilon: mode = 'drag_r_labels' elif button == 3: mode = 'zoom' self._pan_start = cbook.Bunch( rmax = self.get_rmax(), trans = self.transData.frozen(), trans_inverse = self.transData.inverted().frozen(), r_label_angle = self.get_rlabel_position(), x = x, y = y, mode = mode ) def end_pan(self): del self._pan_start def drag_pan(self, button, key, x, y): p = self._pan_start if p.mode == 'drag_r_labels': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) # Deal with theta dt0 = t - startt dt1 = startt - t if abs(dt1) < abs(dt0): dt = abs(dt1) * sign(dt0) * -1.0 else: dt = dt0 * -1.0 dt = (dt / np.pi) * 180.0 self.set_rlabel_position(p.r_label_angle - dt) trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0) trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0) for t in self.yaxis.majorTicks + self.yaxis.minorTicks: t.label1.set_va(vert1) t.label1.set_ha(horiz1) t.label2.set_va(vert2) t.label2.set_ha(horiz2) elif p.mode == 'zoom': startt, startr = p.trans_inverse.transform_point((p.x, p.y)) t, r = p.trans_inverse.transform_point((x, y)) dr = r - startr # Deal with r scale = r / startr self.set_rmax(p.rmax / scale)
def plotInclusiveResponse(dataframe, name): fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(3, 6), constrained_layout=True) fig.suptitle("Inclusive response") trans1 = ax.transData + ScaledTranslation(-5 / 72, 0, fig.dpi_scale_trans) trans2 = ax.transData + ScaledTranslation(+5 / 72, 0, fig.dpi_scale_trans) colors = [sns.xkcd_rgb["cerulean"], sns.xkcd_rgb["rouge"]] gluons_l1l2l3 = dataframe.loc[dataframe.isPhysG == 1, "jetPt"] / dataframe.loc[dataframe.isPhysG == 1, "genJetPt"] uds_l1l2l3 = dataframe.loc[dataframe.isPhysG != 1, "jetPt"] / dataframe.loc[dataframe.isPhysG != 1, "genJetPt"] gluons_dnn = dataframe.loc[dataframe.isPhysG == 1, "response"] uds_dnn = dataframe.loc[dataframe.isPhysG != 1, "response"] mean_g_l1l2l3, std_g_l1l2l3 = norm.fit(gluons_l1l2l3) mean_uds_l1l2l3, std_uds_l1l2l3 = norm.fit(uds_l1l2l3) median_g_l1l2l3 = np.median(gluons_l1l2l3) median_uds_l1l2l3 = np.median(uds_l1l2l3) mean_g_dnn, std_g_dnn = norm.fit(gluons_dnn) mean_uds_dnn, std_uds_dnn = norm.fit(uds_dnn) median_g_dnn = np.median(gluons_dnn) median_uds_dnn = np.median(uds_dnn) iqr_g_l1l2l3 = np.subtract(*np.percentile(gluons_l1l2l3, [75, 25])) * 0.1 iqr_uds_l1l2l3 = np.subtract(*np.percentile(uds_l1l2l3, [75, 25])) * 0.1 iqr_g_dnn = np.subtract(*np.percentile(gluons_dnn, [75, 25])) * 0.1 iqr_uds_dnn = np.subtract(*np.percentile(uds_dnn, [75, 25])) * 0.1 ax.set_xlim(-1.0, 2.0) ax.set_ylim(0.975, 1.04) ax.text(-0.5, 1.041, "60 GeV < p$_T$ < 600 GeV, |$\eta$| < 2.5", fontsize=7) ax.set_ylabel("Median response") ax.set_xlabel("Jet class") plt.errorbar(x=['g', 'uds'], y=[median_g_l1l2l3, median_uds_l1l2l3], fmt='o', label="L1L2L3", color=colors[1], ls='none', ecolor='k', transform=trans1) plt.errorbar(x=['g', 'uds'], y=[median_g_dnn, median_uds_dnn], yerr=[iqr_g_dnn, iqr_uds_dnn], fmt='o', label="DNN", color=colors[0], ls='none', ecolor='k', transform=trans2) ax.plot([-1.0, 2.0], [1.0, 1.0], linestyle='--', linewidth=1.5, color='k') ax.legend() plt.savefig("./plots/InclusiveResponse.pdf".format(name)) plt.clf() plt.close()