def plotPokemon(pokemon1): register_projection(PokemonStatPLot) N = 7 theta = 2*pi * linspace(0, 1, N+1)[:-1] theta += pi/2 labels = ['Max HP', 'Attack', 'Defense', 'Sp. Attack', 'Sp. Defense', 'Speed', 'Mass'] desc1 = [pokemon1.HP, pokemon1.attack, pokemon1.defense, pokemon1.sp_attack, pokemon1.sp_defense, pokemon1.speed, pokemon1.mass_kilo] ax1 = subplot(121, projection='radar') ax1.fill(theta, desc1, pokemon1.color, label=pokemon1.name) for patch in ax1.patches: patch.set_alpha(0.5) ax1.set_varlabels(labels) rgrids((50, 100, 150, 200, 255)) im = pokemon.getAvatar(pokemon1.pokemontype) ax2 = subplot(122) ax2.imshow(im) tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) legend() grid(False) show()
def radar_factory(num_vars, frame="circle"): """Create a radar chart with `num_vars` axes.""" # calculate evenly-spaced axis angles theta = 2 * np.pi * np.linspace(0, 1 - 1.0 / num_vars, num_vars) # rotate theta such that the first axis is at the top theta += np.pi / 2 def draw_poly_frame(self, x0, y0, r): # TODO: use transforms to convert (x, y) to (r, theta) verts = [(r * np.cos(t) + x0, r * np.sin(t) + y0) for t in theta] return plt.Polygon(verts, closed=True, edgecolor="k") def draw_circle_frame(self, x0, y0, r): return plt.Circle((x0, y0), r) frame_dict = {"polygon": draw_poly_frame, "circle": draw_circle_frame} if frame not in frame_dict: raise ValueError, "unknown value for `frame`: %s" % frame class RadarAxes(PolarAxes): """Class for creating a radar chart (a.k.a. a spider or star chart) http://en.wikipedia.org/wiki/Radar_chart """ name = "radar" # use 1 line segment to connect specified points RESOLUTION = 1 # define draw_frame method draw_frame = frame_dict[frame] def fill(self, *args, **kwargs): """Override fill so that line is closed by default""" closed = kwargs.pop("closed", True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180 / np.pi, labels) def _gen_axes_patch(self): x0, y0 = (0.5, 0.5) r = 0.5 return self.draw_frame(x0, y0, r) register_projection(RadarAxes) return theta
def plotPokemons(pokemonList): """ Plots the stats of one or multiple pokemons """ register_projection(PokemonStatPLot) N = 7 theta = 2*pi * linspace(0, 1, N+1)[:-1] theta += pi/2 labels = ['Max HP', 'Attack', 'Defense', 'Sp. Attack', 'Sp. Defense', 'Speed', 'Mass'] for pokemon1 in pokemonList: desc1 = [pokemon1.HP, pokemon1.attack, pokemon1.defense, pokemon1.sp_attack, pokemon1.sp_defense, pokemon1.speed, pokemon1.mass_kilo] ax = subplot(111, projection='radar') ax.fill(theta, desc1, pokemon1.color, label=pokemon1.name) for patch in ax.patches: patch.set_alpha(0.5) ax.set_varlabels(labels) rgrids((50, 100, 150, 200, 255)) legend() grid(True) show()
def radar_factory(num_vars, frame='circle'): theta = np.linspace(0, 2 * np.pi, num_vars, endpoint=False) theta += np.pi / 2 def draw_poly_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def draw_circle_patch(self): return plt.Circle((0.5, 0.5), 0.5) patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch} if frame not in patch_dict: raise ValueError('unknown value for `frame`: %s' % frame) class RadarAxes(PolarAxes): name = 'radar' RESOLUTION = 1 draw_patch = patch_dict[frame] def fill(self, *args, **kwargs): closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(np.degrees(theta), labels) def _gen_axes_patch(self): return self.draw_patch() def _gen_axes_spines(self): if frame == 'circle': return PolarAxes._gen_axes_spines(self) spine_type = 'circle' verts = unit_poly_verts(theta) verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} register_projection(RadarAxes) return theta
def __init__(self,data): data = np.asarray(data) register_projection(NorthPolarAxes) #define important parameters angle = 5 nsection = 360 / angle self.direction = np.linspace(0, 360, nsection, False) / 180 * np.pi #put data in bins frequency = {}#[0] * (nsection) for i in xrange(nsection): frequency[i] = [] for d in data: tmp = int((d[1] - d[1] % angle) / angle) frequency[tmp].append(tmp) #average all freq values freq = [] for k in sorted(frequency.iterkeys()): if len(frequency[k])==0: freq.append(0.) else: freq.append(np.mean(frequency[k])) self.width = angle / 180.0 * np.pi * np.ones(nsection) self.frequency = freq
def __init__(self, data): data = np.asarray(data) register_projection(NorthPolarAxes) #define important parameters angle = 5 nsection = 360 / angle self.direction = np.linspace(0, 360, nsection, False) / 180 * np.pi #put data in bins frequency = {} #[0] * (nsection) for i in xrange(nsection): frequency[i] = [] for d in data: tmp = int((d[1] - d[1] % angle) / angle) frequency[tmp].append(tmp) #average all freq values freq = [] for k in sorted(frequency.iterkeys()): if len(frequency[k]) == 0: freq.append(0.) else: freq.append(np.mean(frequency[k])) self.width = angle / 180.0 * np.pi * np.ones(nsection) self.frequency = freq
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes.""" # calculate evenly-spaced axis angles theta = 2 * np.pi * np.linspace(0, 1 - 1. / num_vars, num_vars) # rotate theta such that the first axis is at the top theta += np.pi / 2 def draw_poly_frame(self, x0, y0, r): # TODO: use transforms to convert (x, y) to (r, theta) verts = [(r * np.cos(t) + x0, r * np.sin(t) + y0) for t in theta] return plt.Polygon(verts, closed=True, edgecolor='k') def draw_circle_frame(self, x0, y0, r): return plt.Circle((x0, y0), r) frame_dict = {'polygon': draw_poly_frame, 'circle': draw_circle_frame} if frame not in frame_dict: raise ValueError, 'unknown value for `frame`: %s' % frame class RadarAxes(PolarAxes): """Class for creating a radar chart (a.k.a. a spider or star chart) http://en.wikipedia.org/wiki/Radar_chart """ name = 'radar' # use 1 line segment to connect specified points RESOLUTION = 1 # define draw_frame method draw_frame = frame_dict[frame] def fill(self, *args, **kwargs): """Override fill so that line is closed by default""" closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180 / np.pi, labels) def _gen_axes_patch(self): x0, y0 = (0.5, 0.5) r = 0.5 return self.draw_frame(x0, y0, r) register_projection(RadarAxes) return theta
def globe_cross_section(): # modified from http://stackoverflow.com/questions/2417794/how-to-make-the-angles-in-a-matplotlib-polar-plot-go-clockwise-with-0-at-the-to from matplotlib.projections import PolarAxes, register_projection from matplotlib.transforms import Affine2D, Bbox, IdentityTransform class GlobeCrossSectionAxes(PolarAxes): """ A variant of PolarAxes where theta starts pointing north and goes clockwise and the radial axis is reversed. """ name = "globe_cross_section" class GlobeCrossSectionTransform(PolarAxes.PolarTransform): def transform(self, tr): xy = num.zeros(tr.shape, num.float_) t = tr[:, 0:1] * d2r r = cake.earthradius - tr[:, 1:2] x = xy[:, 0:1] y = xy[:, 1:2] x[:] = r * num.sin(t) y[:] = r * num.cos(t) return xy transform_non_affine = transform def inverted(self): return GlobeCrossSectionAxes.InvertedGlobeCrossSectionTransform() class InvertedGlobeCrossSectionTransform(PolarAxes.InvertedPolarTransform): def transform(self, xy): x = xy[:, 0:1] y = xy[:, 1:] r = num.sqrt(x * x + y * y) theta = num.arctan2(y, x) * r2d return num.concatenate((theta, cake.earthradius - r), 1) def inverted(self): return GlobeCrossSectionAxes.GlobeCrossSectionTransform() def _set_lim_and_transforms(self): PolarAxes._set_lim_and_transforms(self) self.transProjection = self.GlobeCrossSectionTransform() self.transData = self.transScale + self.transProjection + (self.transProjectionAffine + self.transAxes) self._xaxis_transform = ( self.transProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes ) self._xaxis_text1_transform = self._theta_label1_position + self._xaxis_transform self._yaxis_transform = Affine2D().scale(num.pi * 2.0, 1.0) + self.transData try: rlp = getattr(self, "_r_label1_position") except AttributeError: rlp = getattr(self, "_r_label_position") self._yaxis_text1_transform = rlp + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform register_projection(GlobeCrossSectionAxes)
def _radar_factory(num_vars): theta = _calc_theta(num_vars) def unit_poly_verts(theta): x0, y0, r = [0.5] * 3 verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return verts proj_name = "radar-{}".format(len(theta)) class RadarAxes(PolarAxes): # name = 'radar' RESOLUTION = 1 def fill(self, *args, **kwargs): closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180/np.pi, labels) def _gen_axes_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def _gen_axes_spines(self): spine_type = 'circle' verts = unit_poly_verts(theta) verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} if proj_name not in projection_registry.get_projection_names(): RadarAxes.name = proj_name RadarAxes.theta = theta register_projection(RadarAxes) return theta, proj_name
def _radar_factory(num_vars): theta = _calc_theta(num_vars) def unit_poly_verts(theta): x0, y0, r = [0.5] * 3 verts = [(r * np.cos(t) + x0, r * np.sin(t) + y0) for t in theta] return verts proj_name = "radar-{}".format(len(theta)) class RadarAxes(PolarAxes): # name = 'radar' RESOLUTION = 1 def fill(self, *args, **kwargs): closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180 / np.pi, labels) def _gen_axes_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def _gen_axes_spines(self): spine_type = 'circle' verts = unit_poly_verts(theta) verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} if proj_name not in projection_registry.get_projection_names(): RadarAxes.name = proj_name RadarAxes.theta = theta register_projection(RadarAxes) return theta, proj_name
def radar_factory(num_vars, frame='circle'): """Create a radar chart with num_vars axes.""" # calculate evenly-spaced axis angles theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars) # rotate theta such that the first axis is at the top #theta += np.pi/2 def draw_poly_frame(self, x0, y0, r): # TODO: use transforms to convert (x, y) to (r, theta) verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return plt.Polygon(verts, closed=True, edgecolor='k') def draw_circle_frame(self, x0, y0, r): return plt.Circle((x0, y0), r) frame_dict = {'polygon': draw_poly_frame, 'circle': draw_circle_frame} if frame not in frame_dict: raise ValueError, 'unknown value for `frame`: %s' % frame class RadarAxes(PolarAxes): """ Class for creating a radar chart (a.k.a. a spider or star chart) http://en.wikipedia.org/wiki/Radar_chart """ name = 'radar' # use 1 line segment to connect specified points RESOLUTION = 1 # define draw_frame method draw_frame = frame_dict[frame] def fill(self, *args, **kwargs): """Override fill so that line is closed by default""" closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super(RadarAxes, self).plot(*args, **kwargs) #for line in lines: # self._close_line(line) def set_varlabels(self, labels): self.set_thetagrids(theta * 180/np.pi, labels,fontsize=14) def _gen_axes_patch(self): x0, y0 = (0.5, 0.5) r = 0.5 return self.draw_frame(x0, y0, r) register_projection(RadarAxes) return theta
def test_SequenceDiagram(): df3 = method3_df() _add_tip_angle_and_phase(df3) x3 = [0.0, 0.0, 0.08, 0.08, 0.8] x_data_should_be = [0, 0, 0.08, 0.08, 0.675, 0.8] # Setup matplotlib objects fig = plt.figure() proj.register_projection(SequenceDiagram) axes_obj = fig.add_subplot(projection="sequence_axes") axes_obj.plot_diagram(df3, x3, "1H", "ch1") assert np.allclose(axes_obj.x_data, x_data_should_be)
def __init__(self, data): data = np.asarray(data) register_projection(NorthPolarAxes) #define important parameters angle = 5 nsection = 360 / angle self.direction = np.linspace(0, 360, nsection, False) / 180 * np.pi #put data in bins --- data needs to be 0-360 self.frequency = [0] * (nsection) for i in data: tmp = int((i[1] - i[1] % angle) / angle) self.frequency[tmp] = self.frequency[tmp] + 1 self.width = angle / 180.0 * np.pi * np.ones(nsection)
def __init__(self,data): data = np.asarray(data) register_projection(NorthPolarAxes) #define important parameters angle = 5 nsection = 360 / angle self.direction = np.linspace(0, 360, nsection, False) / 180 * np.pi #put data in bins --- data needs to be 0-360 self.frequency = [0] * (nsection) for i in data: tmp = int((i[1] - i[1] % angle) / angle) self.frequency[tmp] = self.frequency[tmp] + 1 self.width = angle / 180.0 * np.pi * np.ones(nsection)
def _radar_factory(num_vars): theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars) theta += np.pi/2 def unit_poly_verts(theta): x0, y0, r = [1] * 3 verts = [(r*np.cos(t), r*np.sin(t) + 0.1) for t in theta] return verts class RadarAxes(PolarAxes): name = 'radar' RESOLUTION = 1 def fill(self, *args, **kwargs): closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180/np.pi, labels) def _gen_axes_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def _gen_axes_spines(self): spine_type = 'circle' verts = unit_poly_verts(theta) verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} register_projection(RadarAxes) return theta
def _radar_factory(dimensions): def draw_polygon(): vertices = _unit_poly_verts(angles) return plt.Polygon(vertices, closed=True, edgecolor='black') class RadarAxes(PolarAxes): name = 'radar' def fill(self, *args, **kwargs): closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) @staticmethod def _close_line(line): x, y = line.get_data() if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(np.degrees(angles), labels, color='white', weight='bold', size='medium') def _gen_axes_patch(self): return draw_polygon() def _gen_axes_spines(self): verts = _unit_poly_verts(angles) verts.append(verts[0]) spine = Spine(self, 'circle', Path(verts)) spine.set_transform(self.transAxes) return {'polar': spine} angles = np.linspace(0, np.pi * 2, dimensions, endpoint=False) angles += np.pi / 2 register_projection(RadarAxes) return angles
def test_CustomAxes(): # Setup matplotlib objects fig = plt.figure() proj.register_projection(CustomAxes) axes_obj = fig.add_subplot(projection="custom_axes") # _add_rect_with_labels # Test error thrown when no color supplied error = r".*No color in `rect_kwargs`. A color must be specified.*" with pytest.raises(ValueError, match=error): axes_obj._add_rect_with_label(0, 1, "", {"height": 1}) # _add_blank_space_labels axes_obj.make_plot( [1, 2, 2, 3, 3, 4], [0, 1e12, np.nan], "rotor_frequency", [False] * 3, {}, {} )
def radar_factory(): theta = np.linspace(0, 2 * np.pi, 4, endpoint=False) class RadarAxes(PolarAxes): name = 'radar' RESOLUTION = 1 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_theta_zero_location('N') def fill(self, *args, closed=True, **kwargs): return super().fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): lines = super().plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(np.degrees(theta), labels) def _gen_axes_patch(self): return RegularPolygon((0.5, 0.5), 4, radius=.5, edgecolor="k") def _gen_axes_spines(self): spine = Spine(axes=self, spine_type='circle', path=Path.unit_regular_polygon(4)) spine.set_transform(Affine2D().scale(.5).translate(.5, .5) + self.transAxes) return {'polar': spine} register_projection(RadarAxes) return theta
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes.""" theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars) theta += np.pi/2 def draw_poly_frame(self, x0, y0, r): verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return plt.Polygon(verts, closed=True, edgecolor='k') def draw_circle_frame(self, x0, y0, r): return plt.Circle((x0, y0), r) frame_dict = {'polygon': draw_poly_frame, 'circle': draw_circle_frame} if frame not in frame_dict: raise ValueError, 'unknown value for `frame`: %s' % frame class RadarAxes(PolarAxes): """Class for creating a radar chart (a.k.a. a spider or star chart) http://en.wikipedia.org/wiki/Radar_chart """ name = 'radar' RESOLUTION = 1 draw_frame = frame_dict[frame] def fill(self, *args, **kwargs): """Override fill so that line is closed by default""" closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180/np.pi, labels) def _gen_axes_patch(self): x0, y0 = (0.5, 0.5) r = 0.5 return self.draw_frame(x0, y0, r) register_projection(RadarAxes) return theta
def test_MultilineAxes(): x_data = [0, 0, 1, 1, 2, 2, 3, 3] y_data = pd.Series([[1, 1, 1], [1, 0, 0], [1, 0, -1], [1, 1, 0]]) # Setup matplotlib objects fig = plt.figure() proj.register_projection(MultiLineAxes) axes_obj = fig.add_subplot(projection="multi_line_axes") # make_plot # Test y_data dimensions check bad_y_data = pd.Series([0, 1, 2, 3]) # not 2 dimensional error = r".*Symmetry pathway data is misshapen. Data must be 2d.*" with pytest.raises(ValueError, match=error): axes_obj.make_plot(x_data, bad_y_data, "", [], {}, {}) # _offset_overlaps # Test only one symmetry pathway y_data = np.zeros((1, 10)) assert np.array_equal(axes_obj._offset_overlaps(y_data), y_data) # Test overlapping symmetry pathways # Each column represents a symmetry pathway y_data = np.array( [ np.array([1, 1, 1, 1], dtype=float), np.array([1, 0, 0, 1], dtype=float), np.array([1, 0, -1, 0], dtype=float), ] ) offset_should_be = [ [0.91, 0.97, 1.0, 0.94], [1.0, -0.06, 0.0, 1.06], [1.09, 0.06, -1.0, -0.03], ] assert np.allclose(axes_obj._offset_overlaps(y_data), offset_should_be)
def subplot_mosaic(*args, **kwargs): """ Wrapper around matplotlib.pyplot.subplot_mosiac Automatically incorporates the PulseProgram projection in subplot keywords """ register_projection(PulseProgram) if "subplot_kw" in kwargs.keys(): if "projection" in kwargs["subplot_kw"]: warn( f"Projection will be set to 'PulseProgram' instead of {kwargs['subplot_kw']['projection']}" ) kwargs["subplot_kw"]["projection"] = "PulseProgram" else: kwargs["subplot_kw"] = {"projection": "PulseProgram"} fig, ax = plt.subplot_mosaic(*args, **kwargs) return fig, ax
def plot_skewt(p,h,T,Td): """ this code adapted from jhelmus """ # This serves as an intensive exercise of matplotlib's transforms # and custom projection API. This example produces a so-called # SkewT-logP diagram, which is a common plot in meteorology for # displaying vertical profiles of temperature. As far as matplotlib is # concerned, the complexity comes from having X and Y axes that are # not orthogonal. This is handled by including a skew component to the # basic Axes transforms. Additional complexity comes in handling the # fact that the upper and lower X-axes have different data ranges, which # necessitates a bunch of custom classes for ticks,spines, and the axis # to handle this. from matplotlib.axes import Axes import matplotlib.transforms as transforms import matplotlib.axis as maxis import matplotlib.spines as mspines from matplotlib.projections import register_projection # The sole purpose of this class is to look at the upper, lower, or total # interval as appropriate and see what parts of the tick to draw, if any. class SkewXTick(maxis.XTick): def draw(self, renderer): if not self.get_visible(): return renderer.open_group(self.__name__) lower_interval = self.axes.xaxis.lower_interval upper_interval = self.axes.xaxis.upper_interval if self.gridOn and transforms.interval_contains( self.axes.xaxis.get_view_interval(), self.get_loc()): self.gridline.draw(renderer) if transforms.interval_contains(lower_interval, self.get_loc()): if self.tick1On: self.tick1line.draw(renderer) if self.label1On: self.label1.draw(renderer) if transforms.interval_contains(upper_interval, self.get_loc()): if self.tick2On: self.tick2line.draw(renderer) if self.label2On: self.label2.draw(renderer) renderer.close_group(self.__name__) # This class exists to provide two separate sets of intervals to the tick, # as well as create instances of the custom tick class SkewXAxis(maxis.XAxis): def __init__(self, *args, **kwargs): maxis.XAxis.__init__(self, *args, **kwargs) self.upper_interval = 0.0, 1.0 def _get_tick(self, major): return SkewXTick(self.axes, 0, '', major=major) @property def lower_interval(self): return self.axes.viewLim.intervalx def get_view_interval(self): return self.upper_interval[0], self.axes.viewLim.intervalx[1] # This class exists to calculate the separate data range of the # upper X-axis and draw the spine there. It also provides this range # to the X-axis artist for ticking and gridlines class SkewSpine(mspines.Spine): def _adjust_location(self): trans = self.axes.transDataToAxes.inverted() if self.spine_type == 'top': yloc = 1.0 else: yloc = 0.0 left = trans.transform_point((0.0, yloc))[0] right = trans.transform_point((1.0, yloc))[0] pts = self._path.vertices pts[0, 0] = left pts[1, 0] = right self.axis.upper_interval = (left, right) # This class handles registration of the skew-xaxes as a projection as well # as setting up the appropriate transformations. It also overrides standard # spines and axes instances as appropriate. class SkewXAxes(Axes): # The projection must specify a name. This will be used be the # user to select the projection, i.e. ``subplot(111, # projection='skewx')``. name = 'skewx' def _init_axis(self): #Taken from Axes and modified to use our modified X-axis self.xaxis = SkewXAxis(self) self.spines['top'].register_axis(self.xaxis) self.spines['bottom'].register_axis(self.xaxis) self.yaxis = maxis.YAxis(self) self.spines['left'].register_axis(self.yaxis) self.spines['right'].register_axis(self.yaxis) def _gen_axes_spines(self): spines = {'top':SkewSpine.linear_spine(self, 'top'), 'bottom':mspines.Spine.linear_spine(self, 'bottom'), 'left':mspines.Spine.linear_spine(self, 'left'), 'right':mspines.Spine.linear_spine(self, 'right')} return spines def _set_lim_and_transforms(self): """ This is called once when the plot is created to set up all the transforms for the data, text and grids. """ rot = 30 #Get the standard transform setup from the Axes base class Axes._set_lim_and_transforms(self) # Need to put the skew in the middle, after the scale and limits, # but before the transAxes. This way, the skew is done in Axes # coordinates thus performing the transform around the proper origin # We keep the pre-transAxes transform around for other users, like the # spines for finding bounds self.transDataToAxes = self.transScale + (self.transLimits + transforms.Affine2D().skew_deg(rot, 0)) # Create the full transform from Data to Pixels self.transData = self.transDataToAxes + self.transAxes # Blended transforms like this need to have the skewing applied using # both axes, in axes coords like before. self._xaxis_transform = (transforms.blended_transform_factory( self.transScale + self.transLimits, transforms.IdentityTransform()) + transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes # Now register the projection with matplotlib so the user can select # it. register_projection(SkewXAxes) # Now make a simple example using the custom projection. from matplotlib.ticker import ScalarFormatter, MultipleLocator from matplotlib.collections import LineCollection import matplotlib.pyplot as plt from StringIO import StringIO import numpy as np # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=[6.5875, 6.2125]) ax = fig.add_subplot(111, projection='skewx') plt.grid(True) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dicatated by the typical meteorological plot ax.semilogy(T, p, 'r') ax.semilogy(Td, p, 'b') # An example of a slanted line at constant X #l = ax.axvline(0, color='b') # Disables the log-formatting that comes with semilogy ax.yaxis.set_major_formatter(ScalarFormatter()) ax.set_yticks(np.linspace(100,1000,10)) ax.set_ylim(1050,100) ax.xaxis.set_major_locator(MultipleLocator(10)) ax.set_xlim(-50,50) ax.set_xlabel('Temperature (Celsius)', fontsize=18) ax.set_ylabel('Pressure (hPa)', fontsize=18) plt.show()
kwargs.setdefault('horizontalalignment', 'center') args = pos + [disp] self.scatter(*scat, marker='*', zorder=1000, facecolor='gold', edgecolor='black', s=200) self.text(*args, **kwargs) if self.get_title(): pos = self.title.get_position() self.title.set_position((pos[0], pos[1] + 0.05)) self.set_ylim(*ylim) register_projection(EventTableAxes) class _EventTableMetaPlot(type): """Meta-class for generating a new :class:`EventTablePlot`. This object allows the choice of parent class for the `EventTablePlot` to be made at runtime, dependent on the given x-column of the first displayed Table. """ def __call__(cls, *args, **kwargs): """Execute the meta-class, given the arguments for the plot All ``*args`` and ``**kwargs`` are those passed to the `EventTablePlot` constructor, used to determine the appropriate parent class the that object at runtime.
return GalPolarAxes.InvertedGalPolarTransform() class InvertedGalPolarTransform(PolarAxes.InvertedPolarTransform): def transform(self, xy): x = xy[:, 0:1] y = xy[:, 1:] r = sc.sqrt(x * x + y * y) theta = sc.arctan2(y, x) return sc.concatenate((theta, r), 1) def inverted(self): return GalPolarAxes.GalPolarTransform() def _set_lim_and_transforms(self): PolarAxes._set_lim_and_transforms(self) self.transProjection = self.GalPolarTransform() self.transData = (self.transScale + self.transProjection + (self.transProjectionAffine + self.transAxes)) self._xaxis_transform = (self.transProjection + self.PolarAffine( IdentityTransform(), Bbox.unit()) + self.transAxes) self._xaxis_text1_transform = (self._theta_label1_position + self._xaxis_transform) self._yaxis_transform = (Affine2D().scale(sc.pi * 2.0, 1.0) + self.transData) self._yaxis_text1_transform = (self._r_label1_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform) register_projection(GalPolarAxes)
return Axes3D.contour(self, *args, **kwargs) def contourf(self, *args, **kwargs): ''' If the **mantid3d** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes3D.contourf` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid3d'}) ax.contourf(workspace) #for workspaces ax.contourf(x,y,z) #for arrays fig.show() For keywords related to workspaces, see :func:`mantid.plots.plotfunctions3D.contourf` ''' if mantid.plots.helperfunctions.validate_args(*args): mantid.kernel.logger.debug('using mantid.plots.plotfunctions3D') return mantid.plots.plotfunctions3D.contourf(self, *args, **kwargs) else: return Axes3D.contourf(self, *args, **kwargs) register_projection(MantidAxes) register_projection(MantidAxes3D)
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes. """ # calculate evenly-spaced axis angles theta = 2*numpy.pi * numpy.linspace(0, 1-1./num_vars, num_vars) # rotate theta such that the first axis is at the top theta += numpy.pi/2 def draw_poly_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def draw_circle_patch(self): # unit circle centered on (0.5, 0.5) return plt.Circle((0.5, 0.5), 0.5) patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch} if frame not in patch_dict: raise ValueError('unknown value for `frame`: %s' % frame) class RadarAxes(PolarAxes): name = 'radar' # use 1 line segment to connect specified points RESOLUTION = 1 # define draw_frame method draw_patch = patch_dict[frame] def fill(self, *args, **kwargs): """Override fill so that line is closed by default""" closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = numpy.concatenate((x, [x[0]])) y = numpy.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180/numpy.pi, labels) def _gen_axes_patch(self): return self.draw_patch() def _gen_axes_spines(self): if frame == 'circle': return PolarAxes._gen_axes_spines(self) # The following is a hack to get the spines (i.e. the axes frame) # to draw correctly for a polygon frame. # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`. spine_type = 'circle' verts = unit_poly_verts(theta) # close off polygon by repeating first vertex verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} register_projection(RadarAxes) return theta
norm = colors.LogNorm(vmin=vmin, vmax=vmax) kwargs['norm'] = norm x = numpy.concatenate((specvar.frequencies.value, [specvar.x0.value + specvar.dx.value * specvar.shape[0]])) y = specvar.bins.value X, Y = numpy.meshgrid(x, y) mesh = self.pcolormesh(X, Y, specvar.value.T, **kwargs) if len(self.collections) == 1: self.set_yscale('log', nonposy='mask') self.set_xlim(x[0], x[-1]) self.set_ylim(y[0], y[-1]) return mesh register_projection(SpectrumAxes) class SpectrumPlot(Plot): """`Figure` for displaying a :class:`~gwpy.spectrum.core.Spectrum`. """ _DefaultAxesClass = SpectrumAxes def __init__(self, *series, **kwargs): kwargs.setdefault('projection', self._DefaultAxesClass.name) # extract custom keyword arguments sep = kwargs.pop('sep', False) xscale = kwargs.pop( 'xscale', kwargs.pop('logx', True) and 'log' or 'linear') yscale = kwargs.pop( 'yscale', kwargs.pop('logy', True) and 'log' or 'linear')
def radar_factory(num_vars, frame='circle'): """Membuat radar grafik dengan `num_vars` Fungsi ini akan membuat projek RadarAxes dan mengenalkannya Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes. """ #menghitung kedataran ruang dalam sudut sumbu theta = 2 * np.pi * np.linspace(0, 1 - 1. / num_vars, num_vars) #merotasi theta seperti pada sumbu paling atas theta += np.pi / 2 def draw_poly_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def draw_circle_patch(self): #unit lingkaran pada pertengahan return plt.Circle((0.5, 0.5), 0.5) patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch} if frame not in patch_dict: raise ValueError('nilai tidak diketahui pada `frame`: %s' % frame) class RadarAxes(PolarAxes): name = 'radar' #menggunakan satu baris segment untuk menghubungkan point spesifik RESOLUTION = 1 #menjelaskan metode draw_frame draw_patch = patch_dict[frame] def fill(self, *args, **kwargs): #menghindari pengisian garis dengan cepat secara otomatis closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): #menghindari pengisian garis dengan cepat secara otomatis lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # Tetapkan tanda pada x[0], y[0] dengan double if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180 / np.pi, labels) def _gen_axes_patch(self): return self.draw_patch() def _gen_axes_spines(self): if frame == 'circle': return PolarAxes._gen_axes_spines(self) # The following is a hack to get the spines (i.e. the axes frame) # to draw correctly for a polygon frame. # spine_type haruslah 'left', 'right', 'top', 'bottom', or `circle`. spine_type = 'circle' verts = unit_poly_verts(theta) # menghentikan sementara polygon dengan mengulangi vertex awal verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} register_projection(RadarAxes) return theta
return out plot_array2d.__doc__ = SeriesAxes.plot_array2d.__doc__ plot_spectrogram = plot_array2d def _init_epoch_from_array(self, array): """Initialise the epoch of this `TimeSeriesAxes` from the `Array`. This method only operates if the `Axes` only contains a single artist (line, collection, image) and the epoch is currently not set (`== 0`). """ if len(self._get_artists()) == 1 and not self.get_epoch(): return self.set_epoch(array.x0) register_projection(TimeSeriesAxes) class TimeSeriesPlot(SeriesPlot): """`Figure` for displaying a `~gwpy.timeseries.TimeSeries`. Parameters ---------- *series : `TimeSeries` any number of `~gwpy.timeseries.TimeSeries` to display on the plot **kwargs other keyword arguments as applicable for the `~gwpy.plotter.Plot` """
r = sc.sqrt(x*x + y*y) theta = sc.arctan2(y, x) return sc.concatenate((theta, r), 1) def inverted(self): return GalPolarAxes.GalPolarTransform() def _set_lim_and_transforms(self): PolarAxes._set_lim_and_transforms(self) self.transProjection = self.GalPolarTransform() self.transData = ( self.transScale + self.transProjection + (self.transProjectionAffine + self.transAxes)) self._xaxis_transform = ( self.transProjection + self.PolarAffine(IdentityTransform(), Bbox.unit()) + self.transAxes) self._xaxis_text1_transform = ( self._theta_label1_position + self._xaxis_transform) self._yaxis_transform = ( Affine2D().scale(sc.pi * 2.0, 1.0) + self.transData) self._yaxis_text1_transform = ( self._r_label1_position + Affine2D().scale(1.0 / 360.0, 1.0) + self._yaxis_transform) register_projection(GalPolarAxes)
latitude = np.arcsin(y * z) return np.concatenate((longitude, latitude), 1) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ # As before, we need to implement the "transform" method for # compatibility with matplotlib v1.1 and older. if matplotlib.__version__ < "1.2": transform = transform_non_affine def inverted(self): # The inverse of the inverse is the original transform... ;) return HammerAxes.HammerTransform() inverted.__doc__ = Transform.inverted.__doc__ # Now register the projection with matplotlib so the user can select # it. register_projection(HammerAxes) if __name__ == "__main__": import matplotlib.pyplot as plt # Now make a simple example using the custom projection. plt.subplot(111, projection="custom_hammer") p = plt.plot([-1, 1, 1], [-1, -1, 1], "o-") plt.grid(True) plt.show()
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes. """ # calculate evenly-spaced axis angles theta = numpy.linspace(0, 2 * numpy.pi, num_vars, endpoint=False) class RadarAxes(PolarAxes): name = 'radar' # use 1 line segment to connect specified points RESOLUTION = 1 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # rotate plot such that the first axis is at the top self.set_theta_zero_location('N') def fill(self, *args, closed=True, **kwargs): """Override fill so that line is closed by default""" return super().fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super().plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = numpy.concatenate((x, [x[0]])) y = numpy.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(numpy.degrees(theta), labels) def _gen_axes_patch(self): # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5 # in axes coordinates. if frame == 'circle': return Circle((0.5, 0.5), 0.5) elif frame == 'polygon': return RegularPolygon((0.5, 0.5), num_vars, radius=.5, edgecolor="k") else: raise ValueError("unknown value for 'frame': %s" % frame) def _gen_axes_spines(self): if frame == 'circle': return super()._gen_axes_spines() elif frame == 'polygon': # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'. spine = Spine(axes=self, spine_type='circle', path=Path.unit_regular_polygon(num_vars)) # unit_regular_polygon gives a polygon of radius 1 centered at # (0, 0) but we want a polygon of radius 0.5 centered at (0.5, # 0.5) in axes coordinates. spine.set_transform(Affine2D().scale(.5).translate(.5, .5) + self.transAxes) return {'polar': spine} else: raise ValueError("unknown value for 'frame': %s" % frame) register_projection(RadarAxes) return theta
def transform_non_affine(self, xy): #print "transform in:", xy if self.viewer is None: return xy res = np.array(list(map(self._transform_xy, xy))) #print "transform out:", res return res transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ # As before, we need to implement the "transform" method for # compatibility with matplotlib v1.1 and older. if matplotlib.__version__ < '1.2': transform = transform_non_affine def inverted(self): # The inverse of the inverse is the original transform... ;) tform = GingaAxes.GingaTransform() tform.viewer = self.viewer return tform inverted.__doc__ = Transform.inverted.__doc__ # Now register the projection with matplotlib so the user can select # it. register_projection(GingaAxes) #END
for a full description of acceptable ``*args` and ``**kwargs`` """ lim = len(self.collections) out = [] args = list(args) while len(args): if isinstance(args[0], DataQualityFlag): out.append(self.plot_dqflag(args[0], **kwargs)) args.pop(0) continue elif isinstance(args[0], SegmentListDict): out.extend(self.plot_segmentlistdict(args[0], **kwargs)) args.pop(0) continue elif isinstance(args[0], SegmentList): out.extend(self.plot_segmentlist(args[0], **kwargs)) args.pop(0) continue elif isinstance(args[0], Segment): out.append(self.plot_segment(args[0], **kwargs)) args.pop(0) continue break if len(args): out.append(super(TimeSegmentAxes, self).plot(*args, **kwargs)) if not lim: self.set_ylim(-0.1, len(self.collections) + 0.1) return out register_projection(TimeSegmentAxes)
ID to connect <img> tag and <map> tags, default: ``'points'``. This should be unique if multiple maps are to be written to a single HTML file. shape : `str`, optional shape for <area> tag, default: ``'circle'`` standalone : `bool`, optional wrap map HTML with required HTML5 header and footer tags, default: `True` title : `str`, optional title name for standalone HTML page jquery : `str`, optional URL of jquery script, defaults to googleapis.com URL Returns ------- HTML : `str` string of HTML markup that defines the <img> and <map> """ if data is None: artists = self.lines + self.collections + self.images if len(artists) != 1: raise ValueError("Cannot determine artist to map, %d found." % len(artists)) data = artists[0] if isinstance(data, Artist): return html.map_artist(data, imagefile, **kwargs) else: return html.map_data(data, self, imagefile, **kwargs) register_projection(Axes)
from matplotlib.projections import register_projection from pytripgui.canvas_vc.plotter.bars.bar_base import BarBase from pytripgui.canvas_vc.plotter.bars.projection_enum import BarProjection class DosBar(BarBase): name: str = BarProjection.DOS.value def __init__(self, fig, rect, **kwargs): super().__init__(fig, rect, **kwargs) self.label = "Dose" def plot_bar(self, data, **kwargs): super().plot_bar(data) if kwargs['scale'] == "abs": self.bar.set_label("Dose [Gy]") else: self.bar.set_label("Dose [%]") register_projection(DosBar)
(NsNi)) return t * 1e-6 def _t2z(self, t): if self.transform == "linear": return t elif self.transform == "logarithmic": return np.log(np.exp(LAMBDA * t) - 1) elif self.transform == "arcsine": return np.arcsin(1.0 / np.sqrt(1.0 + LAMBDA * self.zeta * G * self.rhod / (np.exp(LAMBDA * t) - 1.0))) register_projection(FTRadialplot) def radialplot(Ns=None, Ni=None, zeta=None, rhod=None, file=None, Dpars=None, transform="logarithmic", **kwargs): """Plot Fission Track counts using a RadialPlot (Galbraith Plot) Args: Ns (list or numpy array, optional): Spontaneous counts.
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes. """ # calculate evenly-spaced axis angles theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False) class RadarAxes(PolarAxes): name = 'radar' # use 1 line segment to connect specified points RESOLUTION = 1 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # rotate plot such that the first axis is at the top self.set_theta_zero_location('N') def fill(self, *args, closed=True, **kwargs): """Override fill so that line is closed by default""" return super().fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super().plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(np.degrees(theta), labels) def _gen_axes_patch(self): # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5 # in axes coordinates. if frame == 'circle': return Circle((0.5, 0.5), 0.5) elif frame == 'polygon': return RegularPolygon((0.5, 0.5), num_vars, radius=.5, edgecolor="k") else: raise ValueError("unknown value for 'frame': %s" % frame) def _gen_axes_spines(self): if frame == 'circle': return super()._gen_axes_spines() elif frame == 'polygon': # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'. spine = Spine(axes=self, spine_type='circle', path=Path.unit_regular_polygon(num_vars)) # unit_regular_polygon gives a polygon of radius 1 centered at # (0, 0) but we want a polygon of radius 0.5 centered at (0.5, # 0.5) in axes coordinates. spine.set_transform(Affine2D().scale(.5).translate(.5, .5) + self.transAxes) return {'polar': spine} else: raise ValueError("unknown value for 'frame': %s" % frame) register_projection(RadarAxes) return theta
return self.LambertTransform( self._center_longitude, self._center_latitude, resolution) def _get_affine_transform(self): return Affine2D() \ .scale(0.25) \ .translate(0.5, 0.5) from matplotlib.projections import register_projection # Now register the projection with matplotlib so the user can select # it. register_projection(MollweideAxes) register_projection(LambertAxes) if __name__ == '__main__': import custom_projection import matplotlib.pyplot as plt import numpy as np # plt.subplot(111, projection="lambert2") plt.subplot(111, projection="mollweide2") # p = plt.plot([-1, 1, 1, 2*np.pi - 0.5, -1 ], [1, -1, 1, -1.3, 1], "o-") # p = plt.plot([0, 8*np.pi, ], [-np.pi/4, np.pi/4], "o-")
def transform_non_affine(self, xy): #print "transform in:", xy if self.viewer is None: return xy res = np.dstack(self.viewer.get_data_xy(xy.T[0], xy.T[1]))[0] #print "transform out:", res return res transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ # As before, we need to implement the "transform" method for # compatibility with matplotlib v1.1 and older. if matplotlib.__version__ < '1.2': transform = transform_non_affine def inverted(self): # The inverse of the inverse is the original transform... ;) tform = GingaAxes.GingaTransform() tform.viewer = self.viewer return tform inverted.__doc__ = Transform.inverted.__doc__ # Now register the projection with matplotlib so the user can select # it. register_projection(GingaAxes) #END
if len(self.collections) == 1: self.set_yscale('log', nonposy='mask') self.set_xlim(x[0], x[-1]) self.set_ylim(y[0], y[-1]) # fill in zeros if isinstance(mesh.norm, colors.LogNorm): cmap = mesh.get_cmap() try: # only listed colormaps have cmap.colors cmap.set_bad(cmap.colors[0]) except AttributeError: pass return mesh register_projection(FrequencySeriesAxes) class FrequencySeriesPlot(Plot): """`Figure` for displaying a `~gwpy.frequencyseries.FrequencySeries` """ _DefaultAxesClass = FrequencySeriesAxes def __init__(self, *series, **kwargs): kwargs.setdefault('projection', self._DefaultAxesClass.name) # extract custom keyword arguments sep = kwargs.pop('sep', False) xscale = kwargs.pop( 'xscale', kwargs.pop('logx', True) and 'log' or 'linear') yscale = kwargs.pop( 'yscale', kwargs.pop('logy', True) and 'log' or 'linear')
shape for <area> tag, default: ``'circle'`` standalone : `bool`, optional wrap map HTML with required HTML5 header and footer tags, default: `True` title : `str`, optional title name for standalone HTML page jquery : `str`, optional URL of jquery script, defaults to googleapis.com URL Returns ------- HTML : `str` string of HTML markup that defines the <img> and <map> """ if data is None: artists = self.lines + self.collections + self.images if len(artists) != 1: raise ValueError("Cannot determine artist to map, %d found." % len(artists)) data = artists[0] if isinstance(data, Artist): return html.map_artist(data, imagefile, **kwargs) else: return html.map_data(data, self, imagefile, **kwargs) register_projection(Axes)
disp += " %s = %.2g" % (column, val) disp = disp.rstrip(',') pos = kwargs.pop('position', [0.5, 1.00]) kwargs.setdefault('transform', self.axes.transAxes) kwargs.setdefault('verticalalignment', 'bottom') kwargs.setdefault('horizontalalignment', 'center') args = pos + [disp] self.scatter(*scat, marker='*', zorder=1000, facecolor='gold', edgecolor='black', s=200) self.text(*args, **kwargs) if self.get_title(): pos = self.title.get_position() self.title.set_position((pos[0], pos[1] + 0.05)) self.set_ylim(*ylim) register_projection(EventTableAxes) class _EventTableMetaPlot(type): """Meta-class for generating a new :class:`EventTablePlot`. This object allows the choice of parent class for the `EventTablePlot` to be made at runtime, dependent on the given x-column of the first displayed Table. """ def __call__(cls, *args, **kwargs): """Execute the meta-class, given the arguments for the plot All ``*args`` and ``**kwargs`` are those passed to the `EventTablePlot` constructor, used to determine the appropriate parent class the that object at runtime.
Returns ------- bins : :class:`~numpy.ndarray` array of bins (length ``len(num)`` + 1). """ if log: return numpy.logspace(log10(lower), log10(upper), num + 1, endpoint=True) else: return numpy.linspace(lower, upper, num + 1, endpoint=True) register_projection(HistogramAxes) class HistogramPlot(Plot): """A plot showing a histogram of data """ _DefaultAxesClass = HistogramAxes def __init__(self, *data, **kwargs): """Generate a new `HistogramPlot` from some ``data``. """ # extract histogram arguments histargs = dict() for key in [ 'bins', 'range', 'normed', 'weights', 'cumulative', 'bottom', 'histtype', 'align', 'orientation', 'rwidth', 'log', 'color',
def _set_lim_from_array(self, array, axis): """Set the axis limits using the index of an `~gwpy.types.Array` """ # get limits from array span span = getattr(array, '{}span'.format(axis)) scale = getattr(self, 'get_{}scale'.format(axis))() if scale == 'log' and not span[0]: # protect log(0) index = getattr(array, '{}index'.format(axis)).value span = index[1], span[1] # set limits set_lim = getattr(self, 'set_{}lim'.format(axis)) return set_lim(*span) register_projection(SeriesAxes) class SeriesPlot(Plot): """`Figure` for displaying a `~gwpy.types.Series`. Parameters ---------- *series : `Series` any number of `~gwpy.types.Series` to display on the plot **kwargs other keyword arguments as applicable for the `~gwpy.plotter.Plot` """ _DefaultAxesClass = SeriesAxes
def plot_skewt(p, h, T, Td): """ this code adapted from jhelmus """ # This serves as an intensive exercise of matplotlib's transforms # and custom projection API. This example produces a so-called # SkewT-logP diagram, which is a common plot in meteorology for # displaying vertical profiles of temperature. As far as matplotlib is # concerned, the complexity comes from having X and Y axes that are # not orthogonal. This is handled by including a skew component to the # basic Axes transforms. Additional complexity comes in handling the # fact that the upper and lower X-axes have different data ranges, which # necessitates a bunch of custom classes for ticks,spines, and the axis # to handle this. from matplotlib.axes import Axes import matplotlib.transforms as transforms import matplotlib.axis as maxis import matplotlib.spines as mspines from matplotlib.projections import register_projection # The sole purpose of this class is to look at the upper, lower, or total # interval as appropriate and see what parts of the tick to draw, if any. class SkewXTick(maxis.XTick): def draw(self, renderer): if not self.get_visible(): return renderer.open_group(self.__name__) lower_interval = self.axes.xaxis.lower_interval upper_interval = self.axes.xaxis.upper_interval if self.gridOn and transforms.interval_contains( self.axes.xaxis.get_view_interval(), self.get_loc()): self.gridline.draw(renderer) if transforms.interval_contains(lower_interval, self.get_loc()): if self.tick1On: self.tick1line.draw(renderer) if self.label1On: self.label1.draw(renderer) if transforms.interval_contains(upper_interval, self.get_loc()): if self.tick2On: self.tick2line.draw(renderer) if self.label2On: self.label2.draw(renderer) renderer.close_group(self.__name__) # This class exists to provide two separate sets of intervals to the tick, # as well as create instances of the custom tick class SkewXAxis(maxis.XAxis): def __init__(self, *args, **kwargs): maxis.XAxis.__init__(self, *args, **kwargs) self.upper_interval = 0.0, 1.0 def _get_tick(self, major): return SkewXTick(self.axes, 0, '', major=major) @property def lower_interval(self): return self.axes.viewLim.intervalx def get_view_interval(self): return self.upper_interval[0], self.axes.viewLim.intervalx[1] # This class exists to calculate the separate data range of the # upper X-axis and draw the spine there. It also provides this range # to the X-axis artist for ticking and gridlines class SkewSpine(mspines.Spine): def _adjust_location(self): trans = self.axes.transDataToAxes.inverted() if self.spine_type == 'top': yloc = 1.0 else: yloc = 0.0 left = trans.transform_point((0.0, yloc))[0] right = trans.transform_point((1.0, yloc))[0] pts = self._path.vertices pts[0, 0] = left pts[1, 0] = right self.axis.upper_interval = (left, right) # This class handles registration of the skew-xaxes as a projection as well # as setting up the appropriate transformations. It also overrides standard # spines and axes instances as appropriate. class SkewXAxes(Axes): # The projection must specify a name. This will be used be the # user to select the projection, i.e. ``subplot(111, # projection='skewx')``. name = 'skewx' def _init_axis(self): #Taken from Axes and modified to use our modified X-axis self.xaxis = SkewXAxis(self) self.spines['top'].register_axis(self.xaxis) self.spines['bottom'].register_axis(self.xaxis) self.yaxis = maxis.YAxis(self) self.spines['left'].register_axis(self.yaxis) self.spines['right'].register_axis(self.yaxis) def _gen_axes_spines(self): spines = { 'top': SkewSpine.linear_spine(self, 'top'), 'bottom': mspines.Spine.linear_spine(self, 'bottom'), 'left': mspines.Spine.linear_spine(self, 'left'), 'right': mspines.Spine.linear_spine(self, 'right') } return spines def _set_lim_and_transforms(self): """ This is called once when the plot is created to set up all the transforms for the data, text and grids. """ rot = 30 #Get the standard transform setup from the Axes base class Axes._set_lim_and_transforms(self) # Need to put the skew in the middle, after the scale and limits, # but before the transAxes. This way, the skew is done in Axes # coordinates thus performing the transform around the proper origin # We keep the pre-transAxes transform around for other users, like the # spines for finding bounds self.transDataToAxes = self.transScale + ( self.transLimits + transforms.Affine2D().skew_deg(rot, 0)) # Create the full transform from Data to Pixels self.transData = self.transDataToAxes + self.transAxes # Blended transforms like this need to have the skewing applied using # both axes, in axes coords like before. self._xaxis_transform = ( transforms.blended_transform_factory( self.transScale + self.transLimits, transforms.IdentityTransform()) + transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes # Now register the projection with matplotlib so the user can select # it. register_projection(SkewXAxes) # Now make a simple example using the custom projection. from matplotlib.ticker import ScalarFormatter, MultipleLocator from matplotlib.collections import LineCollection import matplotlib.pyplot as plt from StringIO import StringIO import numpy as np # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=[6.5875, 6.2125]) ax = fig.add_subplot(111, projection='skewx') plt.grid(True) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dicatated by the typical meteorological plot ax.semilogy(T, p, 'r') ax.semilogy(Td, p, 'b') # An example of a slanted line at constant X #l = ax.axvline(0, color='b') # Disables the log-formatting that comes with semilogy ax.yaxis.set_major_formatter(ScalarFormatter()) ax.set_yticks(np.linspace(100, 1000, 10)) ax.set_ylim(1050, 100) ax.xaxis.set_major_locator(MultipleLocator(10)) ax.set_xlim(-50, 50) ax.set_xlabel('Temperature (Celsius)', fontsize=18) ax.set_ylabel('Pressure (hPa)', fontsize=18) plt.show()
""" return Polygon([[0,0], [0.5,np.sqrt(3)/2], [1,0]], closed=True) # Interactive panning and zooming is not supported with this projection, # so we override all of the following methods to disable it. def can_zoom(self): """ Return True if this axes support the zoom box """ return False def start_pan(self, x, y, button): pass def end_pan(self): pass def drag_pan(self, button, key, x, y): pass # Now register the projection with matplotlib so the user can select # it. register_projection(TriangularAxes) if __name__ == '__main__': import matplotlib.pyplot as plt # Now make a simple example using the custom projection. plt.subplot(111, projection="triangular") p = plt.plot([0, 0.3, 0], [0, 0.3, 1], "o-") plt.grid(True) plt.show()
# wont be called when user moves the polygon with shift+drag. The # drawback of the way it is now is that this function gets called # every time the user clicks on the plot once the polygin has been # created.... #if self.first_time_complete : self.on_polygon_complete(vertices) #self.first_time_complete = False #self.figure.canvas.draw_idle() def on_polygon_complete(self, vertices): """ This method should be overridden/redefined by user. """ print(vertices) # Register the cursorax upon import register_projection(cursorax) register_projection(cursorpolyax) if __name__ == "__main__": import matplotlib.pyplot as plt figsize = (10, 1) fig1 = plt.figure(figsize=figsize) #ax = fig.add_subplot(111, projection='cursor') ax1 = fig1.add_axes([0, 0, 1, 0.5]) #fig2 = plt.figure(figsize=figsize) ax2 = fig1.add_axes([0, 0.5, 1, 0.5]) ax2.set_xticks([]) r = range(256) d = np.array([r]) ax1.pcolormesh(d, cmap='viridis')
# if label has been moved, reset things try: tick.set_bbox(tick._orig_bbox) except AttributeError: pass else: tick.set_horizontalalignment(tick._orig_ha) tick.set_position(tick._orig_pos) del tick._orig_bbox del tick._orig_ha del tick._orig_pos return super(SegmentAxes, self).draw(*args, **kwargs) draw.__doc__ = TimeSeriesAxes.draw.__doc__ register_projection(SegmentAxes) class SegmentPlot(TimeSeriesPlot): """`Figure` for displaying a `~gwpy.segments.DataQualityFlag`. Parameters ---------- *flags : `DataQualityFlag` any number of `~gwpy.segments.DataQualityFlag` to display on the plot insetlabels : `bool`, default: `False` display segment labels inside the axes. Prevents very long segment names from getting squeezed off the end of a standard figure **kwargs other keyword arguments as applicable for the `~gwpy.plotter.Plot`
return np.column_stack([longitude, latitude]) transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__ def inverted(self): return HammerAxes.HammerTransform(self._resolution) inverted.__doc__ = Transform.inverted.__doc__ def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 GeoAxes.__init__(self, *args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.cla() def _get_core_transform(self, resolution): return self.HammerTransform(resolution) # Now register the projection with matplotlib so the user can select # it. register_projection(HammerAxes) if __name__ == '__main__': import matplotlib.pyplot as plt # Now make a simple example using the custom projection. plt.subplot(111, projection="custom_auger") #p = plt.plot([-1, 1, 1], [-1, -1, 1], "o-") plt.grid(True) plt.show()
try: tick.set_bbox(tick._orig_bbox) except AttributeError: pass else: tick.set_horizontalalignment(tick._orig_ha) tick.set_position(tick._orig_pos) del tick._orig_bbox del tick._orig_ha del tick._orig_pos return super(SegmentAxes, self).draw(*args, **kwargs) draw.__doc__ = TimeSeriesAxes.draw.__doc__ register_projection(SegmentAxes) class SegmentPlot(TimeSeriesPlot): """`Figure` for displaying a :class:`~gwpy.segments.DataQualityFlag`. Parameters ---------- *flags : `DataQualityFlag` any number of :class:`~gwpy.segments.DataQualityFlag` to display on the plot insetlabels : `bool`, default: `False` display segment labels inside the axes. Prevents very long segment names from getting squeezed off the end of a standard figure **kwargs other keyword arguments as applicable for the
import numpy as np import matplotlib.pyplot as pl from matplotlib.projections import register_projection from NorthPolarAxes import NorthPolarAxes import ConfigParser config = ConfigParser.ConfigParser() config.read('configure') filename = config.get('configure', 'filename') angle = int(config.get('configure', 'angle')) register_projection(NorthPolarAxes) data = np.genfromtxt(filename) nsection = 360 / angle direction = np.linspace(0, 360, nsection, False) / 180 * np.pi print direction frequency = [0] * (nsection) for i in range(len(data)): tmp = int((data[i][1] - data[i][1] % angle) / angle) frequency[tmp] = frequency[tmp] + 1 width = angle / 180.0 * np.pi * np.ones(nsection) ax = pl.subplot(1, 1, 1, projection='northpolar') bars = ax.bar(direction, frequency, width=width, bottom=0.0) for r, bar in zip(frequency, bars): bar.set_facecolor(pl.cm.jet(0.8)) bar.set_edgecolor('grey') bar.set_alpha(0.8) pl.show()
from matplotlib.projections import register_projection from hambiplots.smithplot.smithaxes import SmithAxes import matplotlib # check version requierment if matplotlib.__version__ < '1.2': raise ImportError("pySmithPlot requires at least matplotlib version 1.2") # add smith projection to available projections register_projection(SmithAxes)
Geophysical Research, Vol. 64, No. 11, pp. 1891--1909. """ lon, lat, totals, kwargs = self._contour_helper(args, kwargs) return self.contourf(lon, lat, totals, **kwargs) class EqualAngleAxes(StereonetAxes): """An axes representing a lower-hemisphere "Wulff" (a.k.a. equal angle) projection.""" _base_transform = stereonet_transforms.StereographicTransform _scale = 2.0 name = 'equal_angle_stereonet' class EqualAreaAxes(StereonetAxes): """An axes representing a lower-hemisphere "Schmitt" (a.k.a. equal area) projection.""" name = 'equal_area_stereonet' # We need to define explict subplot classes so that we don't mess up the # method resolution order when using matplotlib subplots. EqualAngleAxesSubplot = subplot_class_factory(EqualAngleAxes) EqualAngleAxesSubplot.__module__ = EqualAngleAxes.__module__ EqualAreaAxesSubplot = subplot_class_factory(EqualAngleAxes) EqualAreaAxesSubplot.__module__ = EqualAngleAxes.__module__ register_projection(StereonetAxes) register_projection(EqualAreaAxes) register_projection(EqualAngleAxes)
LOGINT = xu.maplog(self.gridder.data.transpose(), 6, 0) # draw rsm self.cs = self.contourf(self.gridder.xaxis, self.gridder.yaxis, LOGINT, 25, extend="min") # annotate axis self.set_xlabel(r"$Q_{x}$") self.set_ylabel(r"$Q_{z}$") def set_gridder_resolution(self, nx, ny): # update gridder self.gridder.SetResolution(nx, ny) # regrid data self.gridder(self.Qx_data, self.Qz_data, self.Int_data) LOGINT = xu.maplog(self.gridder.data.transpose(), 6, 0) # draw rsm cmin, cmax = self.cs.get_clim() self.cs = self.contourf(self.gridder.xaxis, self.gridder.yaxis, LOGINT, 25, extend="min") self.cs.set_clim(cmin, cmax) def set_data_limits(self, cmin, cmax): self.cs.set_clim(cmin, cmax) # TODO if there is a colorbar, deal with it as well # register new axes type register_projection(CustomMplAxes)
def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes. """ # calculate evenly-spaced axis angles theta = np.linspace(0, 2 * np.pi, num_vars, endpoint=False) # rotate theta such that the first axis is at the top theta += np.pi / 2 def draw_poly_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def draw_circle_patch(self): # unit circle centered on (0.5, 0.5) return plt.Circle((0.5, 0.5), 0.5) patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch} if frame not in patch_dict: raise ValueError('unknown value for `frame`: %s' % frame) class RadarAxes(PolarAxes): name = 'radar' # use 1 line segment to connect specified points RESOLUTION = 1 # define draw_frame method draw_patch = patch_dict[frame] def fill(self, *args, **kwargs): """Override fill so that line is closed by default""" closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(np.degrees(theta), labels) def _gen_axes_patch(self): return self.draw_patch() def _gen_axes_spines(self): if frame == 'circle': return PolarAxes._gen_axes_spines(self) # The following is a hack to get the spines (i.e. the axes frame) # to draw correctly for a polygon frame. # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`. spine_type = 'circle' verts = unit_poly_verts(theta) # close off polygon by repeating first vertex verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} register_projection(RadarAxes) return theta
log : `bool`, optional, default: `False` if `True` generate logarithmically-spaced bins, else generate linearly-spaced bins. Returns ------- bins : `~numpy.ndarray` array of bins (length ``len(num)`` + 1). """ if log: return numpy.logspace(log10(lower), log10(upper), num+1, endpoint=True) return numpy.linspace(lower, upper, num+1, endpoint=True) register_projection(HistogramAxes) class HistogramPlot(Plot): """A plot showing a histogram of data """ _DefaultAxesClass = HistogramAxes def __init__(self, *data, **kwargs): """Generate a new `HistogramPlot` from some ``data``. """ # separate keyword arguments axargs, histargs = self._parse_kwargs(kwargs) # generate Figure super(HistogramPlot, self).__init__(**kwargs)
transforms.IdentityTransform()) + transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes @property def lower_xlim(self): return self.axes.viewLim.intervalx @property def upper_xlim(self): pts = [[0., 1.], [1., 1.]] return self.transDataToAxes.inverted().transform(pts)[:, 0] # Now register the projection with matplotlib so the user can select # it. register_projection(SkewXAxes) if __name__ == '__main__': # Now make a simple example using the custom projection. from io import StringIO from matplotlib.ticker import (MultipleLocator, NullFormatter, ScalarFormatter) import matplotlib.pyplot as plt import numpy as np # Some examples data data_txt = ''' 978.0 345 7.8 0.8 61 4.16 325 14 282.7 294.6 283.4 971.0 404 7.2 0.2 61 4.01 327 17 282.7 294.2 283.4 946.7 610 5.2 -1.8 61 3.56 335 26 282.8 293.0 283.4 944.0 634 5.0 -2.0 61 3.51 336 27 282.8 292.9 283.4
self.set_ylim(*spectrogram.band) if not self.get_ylabel(): self.add_label_unit(spectrogram.yunit, axis='y') # reset grid if grid[0]: self.xaxis.grid(True, 'major') if grid[1]: self.xaxis.grid(True, 'minor') if grid[2]: self.yaxis.grid(True, 'major') if grid[3]: self.yaxis.grid(True, 'minor') return mesh register_projection(TimeSeriesAxes) class TimeSeriesPlot(Plot): """`Figure` for displaying a :class:`~gwpy.timeseries.TimeSeries`. Parameters ---------- *series : `TimeSeries` any number of :class:`~gwpy.timeseries.TimeSeries` to display on the plot **kwargs other keyword arguments as applicable for the :class:`~gwpy.plotter.Plot` """ _DefaultAxesClass = TimeSeriesAxes