本文整理汇总了Python中matplotlib.projections.register_projection函数的典型用法代码示例。如果您正苦于以下问题:Python register_projection函数的具体用法?Python register_projection怎么用?Python register_projection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了register_projection函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:sokolo986,项目名称:CS109_Volcano,代码行数:27,代码来源:rosePlot.py
示例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
开发者ID:jkseppan,项目名称:matplotlib.github.com,代码行数:60,代码来源:radar_chart.py
示例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()
开发者ID:alex011235,项目名称:pokemon,代码行数:28,代码来源:pokemon_plot.py
示例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()
开发者ID:alex011235,项目名称:pokemon,代码行数:29,代码来源:pokemon_plot.py
示例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)
开发者ID:josephwinston,项目名称:pyrocko,代码行数:59,代码来源:cake_plot.py
示例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
开发者ID:jasonmhite,项目名称:jplotlib,代码行数:53,代码来源:radar_plot.py
示例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
开发者ID:OpenMPToolsInterface,项目名称:LLVM-openmp,代码行数:52,代码来源:summarizeStats.py
示例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
开发者ID:stefco,项目名称:gwpy,代码行数:31,代码来源:series.py
示例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()
开发者ID:Teslos,项目名称:pycalphad,代码行数:31,代码来源:triangular.py
示例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')
开发者ID:rpfisher,项目名称:gwpy,代码行数:31,代码来源:frequencyseries.py
示例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.
开发者ID:gitter-badger,项目名称:gwpy,代码行数:31,代码来源:table.py
示例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)
开发者ID:hambi-hemts,项目名称:hambiplots,代码行数:10,代码来源:__init__.py
示例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
开发者ID:rpfisher,项目名称:gwpy,代码行数:31,代码来源:timeseries.py
示例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
开发者ID:ianthomas23,项目名称:matplotlib,代码行数:78,代码来源:radar_chart.py
示例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)
开发者ID:samueljackson92,项目名称:mantid,代码行数:30,代码来源:__init__.py
示例16: inverted
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()
开发者ID:carlrose,项目名称:matplotlib,代码行数:30,代码来源:custom_projection_example.py
示例17: transform_non_affine
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
开发者ID:AlexaVillaume,项目名称:ginga,代码行数:29,代码来源:transform.py
示例18: len
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)
开发者ID:isunspot,项目名称:gwpy,代码行数:30,代码来源:axes.py
示例19: _get_affine_transform
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-")
开发者ID:pelson,项目名称:mpl_mapping_trial,代码行数:29,代码来源:OLD_custom_projection.py
示例20: plot_skewt
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)
#.........这里部分代码省略.........
开发者ID:EVS-ATMOS,项目名称:HRRR,代码行数:101,代码来源:plot_skewt.py
注:本文中的matplotlib.projections.register_projection函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论