本文整理汇总了Python中matplotlib.projections.register_projection函数的典型用法代码示例。如果您正苦于以下问题:Python register_projection函数的具体用法?Python register_projection怎么用?Python register_projection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了register_projection函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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
示例2: radar_factory
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
示例3: plotPokemons
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()
示例4: plotPokemon
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()
示例5: globe_cross_section
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)
示例6: _radar_factory
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
示例7: radar_factory
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
示例8: _set_lim_from_array
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
示例9: Polygon
"""
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()
示例10: len
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')
示例11: register_projection
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.
示例12: ImportError
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)
示例13: register_projection
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
示例14: radar_factory
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
示例15: contourf
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)