本文整理汇总了Python中matplotlib.transforms.offset_copy函数的典型用法代码示例。如果您正苦于以下问题:Python offset_copy函数的具体用法?Python offset_copy怎么用?Python offset_copy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了offset_copy函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: rainbow_text
def rainbow_text(x, y, strings, colors, ax=None, **kw):
"""
Take a list of ``strings`` and ``colors`` and place them next to each
other, with text strings[i] being shown in colors[i].
This example shows how to do both vertical and horizontal text, and will
pass all keyword arguments to plt.text, so you can set the font size,
family, etc.
The text will get added to the ``ax`` axes, if provided, otherwise the
currently active axes will be used.
"""
if ax is None:
ax = plt.gca()
t = ax.transData
canvas = ax.figure.canvas
# horizontal version
for s, c in zip(strings, colors):
text = ax.text(x, y, " " + s + " ", color=c, transform=t, **kw)
text.draw(canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
# vertical version
for s, c in zip(strings, colors):
text = ax.text(x, y, " " + s + " ", color=c, transform=t,
rotation=90, va='bottom', ha='center', **kw)
text.draw(canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
开发者ID:7924102,项目名称:matplotlib,代码行数:31,代码来源:rainbow_text.py
示例2: rainbow_text
def rainbow_text(x,y,ls,lc,**kw):
"""
Take a list of strings ``ls`` and colors ``lc`` and place them next to each
other, with text ls[i] being shown in color lc[i].
This example shows how to do both vertical and horizontal text, and will
pass all keyword arguments to plt.text, so you can set the font size,
family, etc.
"""
t = plt.gca().transData
fig = plt.gcf()
#### note: this line moved down ....###
#plt.show() #
#######################################
#horizontal version
for s,c in zip(ls,lc):
text = plt.text(x,y," "+s+" ",color=c, transform=t,fontsize=15,bbox=bb **kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
#vertical version
for s,c in zip(ls,lc):
text = plt.text(x,y," "+s+" ",color=c, transform=t,
rotation=90,va='bottom',ha='center',**kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
t = plt.gca().transData
fig = plt.gcf()
plt.show() ############### when this is here, you can see that
开发者ID:LibCorner,项目名称:matplot_note,代码行数:33,代码来源:text_color.py
示例3: relations
def relations(xss, yss, filename, xlabel=None, ylabel=None, pointlabels = [],
xlim = None, labels = []):
xss = list(xss)
yss = list(yss)
plt.clf()
fig = plt.figure()
ax = plt.subplot(111)
trans_offset = mtrans.offset_copy(ax.transData, fig=fig, x = 0.05, y = 0.1, units='inches')
if len(labels) < len(xss):
labels += [''] * (len(xss) - len(labels))
for xsl, ysl, c, label in zip(xss, yss, plt.cm.Dark2(np.linspace(0, 1, len(xss))), labels):
ax.scatter(xsl, ysl, c = c, alpha=0.5, label=label)
if pointlabels:
for x, y, l in zip(xsl, ysl, pointlabels):
ax.text(x, y, l, transform = trans_offset, fontsize=8)
if xlabel:
ax.set_xlabel(xlabel)
if ylabel:
ax.set_ylabel(ylabel)
if xlim is not None:
ax.set_xlim(xlim)
plt.legend(loc='upper center', prop={'size': 10}, bbox_to_anchor=(0.5,1.1), ncol=int(math.ceil(len(xss)/2.0)), fancybox=True)
ax.grid(True)
fig.savefig(filename, dpi=100)
plt.close(fig)
开发者ID:Droggelbecher,项目名称:experiment-utils,代码行数:35,代码来源:plots.py
示例4: relation
def relation(xs, ys, filename, xlabel=None, ylabel=None, pointlabels = [],
xlim = None, xlog = False, vertical_line = None):
xsl = list(xs)
ysl = list(ys)
plt.clf()
fig = plt.figure()
ax = plt.subplot(111)
trans_offset = mtrans.offset_copy(ax.transData, fig=fig, x = 0.05, y = 0.1, units='inches')
ax.scatter(xsl, ysl, c = plt.cm.Set1(np.linspace(0, 1, len(xsl))), alpha=0.5)
if xlabel:
ax.set_xlabel(xlabel)
if ylabel:
ax.set_ylabel(ylabel)
if xlim is not None:
ax.set_xlim(xlim)
if xlog:
ax.set_xscale('log')
if pointlabels:
for x, y, l in zip(xsl, ysl, pointlabels):
ax.text(x, y, l, transform = trans_offset, fontsize=8)
if vertical_line:
ax.axvline(vertical_line, color='red')
ax.grid(True)
fig.savefig(filename, dpi=100)
plt.close(fig)
开发者ID:Droggelbecher,项目名称:experiment-utils,代码行数:34,代码来源:plots.py
示例5: squares
def squares(plot, p, colors='r', size=15, xoff=0, yoff=0, alpha=1.0,
zorder=1000):
"""
Draw a square at given node
Args:
plot (Tree): A Tree plot instance
p: A node or list of nodes
colors: Str or list of strs. Colors of squares to be drawn.
Optional, defaults to 'r' (red)
size (float): Size of the squares. Optional, defaults to 15
xoff, yoff (float): Offset for x and y dimensions. Optional,
defaults to 0.
alpha (float): between 0 and 1. Alpha transparency of squares.
Optional, defaults to 1 (fully opaque)
zorder (int): The drawing order. Higher numbers appear on top
of lower numbers. Optional, defaults to 1000.
"""
points = _xy(plot, p)
trans = offset_copy(
plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points')
col = RegularPolyCollection(
numsides=4, rotation=pi*0.25, sizes=(size*size,),
offsets=points, facecolors=colors, transOffset=trans,
edgecolors='none', alpha=alpha, zorder=zorder
)
plot.add_collection(col)
plot.figure.canvas.draw_idle()
开发者ID:rhr,项目名称:ivy,代码行数:31,代码来源:symbols.py
示例6: Text
def Text(x, y, txt, x_offset=0, y_offset=0, units="points", va="bottom", ha="left", color="black", fontsize=10):
"""
Add text
========
"""
trans = offset_copy(gca().transData, fig=gcf(), x=x_offset, y=y_offset, units=units)
text(x, y, txt, transform=trans, va=va, ha=ha, color=color, fontsize=fontsize)
开发者ID:cpmech,项目名称:cmodel,代码行数:7,代码来源:gosl.py
示例7: add_circles
def add_circles(treeplot, nodes, colors="g", size=15, xoff=0, yoff=0, vis=True):
"""
Draw circles on plot
Args:
nodes: A node object or list of Node objects or label or list of labels
colors: Str or list of strs. Colors of the circles. Optional,
defaults to 'g' (green)
size (float): Size of the circles. Optional, defaults to 15
xoff, yoff (float): X and Y offset. Optional, defaults to 0.
"""
points = xy(treeplot, nodes)
trans = offset_copy(
treeplot.transData, fig=treeplot.figure, x=xoff, y=yoff, units='points'
)
col = CircleCollection(
sizes=(pi*size*size*0.25,),
offsets=points, facecolors=colors, transOffset=trans,
edgecolors='none', zorder=1
)
col.set_visible(vis)
treeplot.add_collection(col)
treeplot.figure.canvas.draw_idle()
开发者ID:ChriZiegler,项目名称:ivy,代码行数:26,代码来源:layers.py
示例8: update_fig
def update_fig(self):
from matplotlib import pyplot as plt
from matplotlib import transforms
xlim, ylim = zip((0, 0), self.dimensions)
if not hasattr(self, 'fig'):
plt.axis('off')
self.fig = plt.figure()
self.plt = self.fig.add_subplot(111,
axisbg='k',
aspect='equal')
offset = transforms.offset_copy(self.plt.transData,
x=5, y=5, units='dots')
# bucket patches
buckets = {'b': [],
'r': []}
for cell in self.space.cells():
if cell.agents:
buckets[cell.agents.copy().pop().color[0]].append(cell.point)
self.plt.clear()
for b, points in buckets.items():
self.plt.plot(*zip(*points), marker='o',
markerfacecolor=b,
linestyle='None',
markersize=8,
transform=offset)
# need to do this on OSX
self.plt.set_xlim(*xlim)
self.plt.set_ylim(*ylim)
开发者ID:unthingable,项目名称:Agentum,代码行数:34,代码来源:schelling.py
示例9: circles
def circles(plot, p, colors='g', size=15, xoff=0, yoff=0):
"""
Draw circles on plot
Args:
plot (Tree): A Tree plot instance
p: A node object or list of Node objects
colors: Str or list of strs. Colors of the circles. Optional,
defaults to 'g' (green)
size (float): Size of the circles. Optional, defaults to 15
xoff, yoff (float): X and Y offset. Optional, defaults to 0.
"""
points = _xy(plot, p)
trans = offset_copy(
plot.transData, fig=plot.figure, x=xoff, y=yoff, units='points'
)
col = CircleCollection(
sizes=(pi*size*size*0.25,),
offsets=points, facecolors=colors, transOffset=trans,
edgecolors='none'
)
plot.add_collection(col)
plot.figure.canvas.draw_idle()
return col
开发者ID:rhr,项目名称:ivy,代码行数:27,代码来源:symbols.py
示例10: _offset
def _offset(ax, x, y):
"""Provide offset in pixels
Parameters
----------
x : int
Offset in pixels for x
y : int
Offset in pixels for y
Idea borrowed from
http://www.scipy.org/Cookbook/Matplotlib/Transformations
but then heavily extended to be compatible with many
reincarnations of matplotlib
"""
d = dir(mlt)
if "offset_copy" in d:
# tested with python-matplotlib 0.98.3-5
# ??? if pukes, might need to replace 2nd parameter from
# ax to ax.get_figure()
return mlt.offset_copy(ax.transData, ax, x=x, y=y, units="dots")
elif "BlendedAffine2D" in d:
# some newer versions of matplotlib
return ax.transData + mlt.Affine2D().translate(x, y)
elif "blend_xy_sep_transform" in d:
trans = mlt.blend_xy_sep_transform(ax.transData, ax.transData)
# Now we set the offset in pixels
trans.set_offset((x, y), mlt.identity_transform())
return trans
else:
raise RuntimeError, "Lacking needed functions in matplotlib.transform " "for _offset. Please upgrade"
开发者ID:robbisg,项目名称:PyMVPA,代码行数:31,代码来源:erp.py
示例11: get_text_trans
def get_text_trans(cls, figure):
"return transformation for text labels"
from matplotlib.transforms import offset_copy
return offset_copy(figure.gca().transData, figure.figure,
cls.miscProp["textOffsetX"],
cls.miscProp["textOffsetY"],
units="points")
开发者ID:gizela,项目名称:gizela,代码行数:7,代码来源:PointStyle.py
示例12: main
def main():
# Create a Stamen Terrain instance.
stamen_terrain = cimgt.StamenTerrain()
# Create a GeoAxes in the tile's projection.
ax = plt.axes(projection=stamen_terrain.crs)
# Limit the extent of the map to a small longitude/latitude range.
ax.set_extent([-22, -15, 63, 65])
# Add the Stamen data at zoom level 8.
ax.add_image(stamen_terrain, 8)
# Add a marker for the Eyjafjallajökull volcano.
plt.plot(-19.613333, 63.62, marker='o', color='red', markersize=12,
alpha=0.7, transform=ccrs.Geodetic())
# Use the cartopy interface to create a matplotlib transform object
# for the Geodetic coordinate system. We will use this along with
# matplotlib's offset_copy function to define a coordinate system which
# translates the text by 25 pixels to the left.
geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax)
text_transform = offset_copy(geodetic_transform, units='dots', x=-25)
# Add text 25 pixels to the left of the volcano.
plt.text(-19.613333, 63.62, u'Eyjafjallajökull',
verticalalignment='center', horizontalalignment='right',
transform=text_transform,
bbox=dict(facecolor='sandybrown', alpha=0.5, boxstyle='round'))
plt.show()
开发者ID:zak-k,项目名称:cartopy,代码行数:30,代码来源:eyja_volcano.py
示例13: main
def main():
# Create a Stamen Terrain instance.
terrain = cimgt.StamenTerrain()
# Create a GeoAxes in the tile's projection.
plt.figure(figsize=(10,10))
ax = plt.axes(projection=terrain.crs)
# Limit the extent of the map to a small longitude/latitude range.
ax.set_extent([-122.3, -122, 46.1, 46.3])
# Add the MapQuest data at zoom level 8.
ax.add_image(terrain, 12)
# Add a marker for the Mount Saint Helens volcano.
plt.plot(-122.189611,46.205868, marker='o', color='yellow', markersize=12,
alpha=0.7, transform=ccrs.Geodetic())
# Use the cartopy interface to create a matplotlib transform object
# for the Geodetic coordinate system. We will use this along with
# matplotlib's offset_copy function to define a coordinate system which
# translates the text by 25 pixels to the left.
geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax)
text_transform = offset_copy(geodetic_transform, units='dots', x=-25)
# Add text 25 pixels to the left of the volcano.
plt.text(-122.189611,46.205868, u'Mount Saint Helens Volcano',
verticalalignment='center', horizontalalignment='right',
transform=text_transform,
bbox=dict(facecolor='wheat', alpha=0.5, boxstyle='round'))
gl=ax.gridlines(draw_labels=True)
gl.xlabels_top = False
gl.ylabels_right = False
plt.show()
开发者ID:ivn888,项目名称:notebook,代码行数:34,代码来源:Cartopy_terrain.py
示例14: plot_array
def plot_array(array, visibilities=None):
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
transOffset = offset_copy(ax.transData, fig=ax.figure, x = 0.0, y=-0.10, units='inches')
center = array.arrxyz
# Calculate a "east" unit vector
east = np.array([center[1]*center[2],-center[0]*center[2],0])
if center[2] > 0: east *= -1
east /= np.sqrt(np.sum(np.square(east)))
# Calculate a "north" unit vector
north = np.cross(center, east)
north /= np.sqrt(np.sum(np.square(north)))
stations = array.station
xlist = []
ylist = []
for station in stations:
if 'U' in station.sta_name:
color='green'
else:
color='blue'
x = np.inner(station.staxyz, east)
y = np.inner(station.staxyz, north)
xlist.append(x)
ylist.append(y)
ax.plot([x], [y], 'o', color=color, markersize=1+station.diameter)
plt.text(x, y, station.sta_name, transform=transOffset, horizontalalignment='center', verticalalignment='top', family='serif')
if visibilities:
for vis in visibilities:
x = np.array([np.inner(vis.station[0].staxyz, east), np.inner(vis.station[1].staxyz, east)])
y = np.array([np.inner(vis.station[0].staxyz, north), np.inner(vis.station[1].staxyz, north)])
ax.plot(x, y, linestyle='-', marker='|', markersize=20, label=vis.station[0].sta_name + vis.station[1].sta_name)
ax.plot([0], [0], 'r+')
plt.text(0, 0, '$\\vec{O}$', transform=transOffset, horizontalalignment='center', verticalalignment='top')
ax.annotate('N', xy=(0.05, 0.25), xytext=(0.05, 0.05), xycoords='axes fraction', textcoords='axes fraction', arrowprops={'width':2}, horizontalalignment='center', verticalalignment='bottom', family='serif', size='20')
minx = np.min(xlist)
miny = np.min(ylist)
maxx = np.max(xlist)
maxy = np.max(ylist)
centerx = (maxx - minx) / 2.0 + minx
centery = (maxy - miny) / 2.0 + miny
width = 1.1*np.max([maxx - minx, maxy - miny])
ax.set_xlim(centerx - width / 2.0, centerx + width / 2.0)
ax.set_ylim(centery - width / 2.0, centery + width / 2.0)
ax.relim()
ax.set_xlabel('Relative position (m)')
ax.set_ylabel('Relative position (m)')
开发者ID:danmoser,项目名称:pyhdust,代码行数:59,代码来源:oitools.py
示例15: circles
def circles(plot, points, colors, size=15, xoff=0, yoff=0):
trans = offset_copy(plot.transData, fig=plot.figure, x=xoff, y=yoff, units="points")
col = CircleCollection(
sizes=(pi * size * size * 0.25,), offsets=points, facecolors=colors, transOffset=trans, edgecolors="none"
)
return plot.add_collection(col)
开发者ID:nonumberjim,项目名称:PhylografterNeo4j,代码行数:8,代码来源:shapes.py
示例16: plotLogo
def plotLogo(fig, ax, heights, charXDist=10):
""" draw a sequence logo onto axis. heights is a list of dictionaries with letter -> float
>>> freqs = [{"A":0.5, "C":0.3}, {"T":0.3, "G":0.7}]
>>> fig.set_size_inches(3,0.5*len(freqs))
>>> plotLogo(fig, ax, freqs)
"""
#ax.set_xlim(0,len(heights))
ax.set_ylim(-1,1)
ax.axis('off')
#t = plt.gca().transData
t = ax.transData
xPos = 0.0
charToCol = {"C":"b", "A":"r", "T":"k", "G":"y"}
for yDict in heights:
if len(yDict)==0:
yDict["A"]=0.0
charFreqs = yDict.items()
charFreqs.sort(key=operator.itemgetter(1))
#yZeroT = transforms.offset_copy(t, units="dots")
lastFreq = None
# need to draw something, otherwise we don't know the width to advance
for char, freq in charFreqs:
# jump back to y=0 when we switch from negative to positive freqs
#print char, freq
if lastFreq == None or (lastFreq < 0 and freq > 0):
#t = transforms.offset_copy(text._transform, y=0, units='dots')
#t = yZeroT
t = transforms.offset_copy(ax.transData, x=xPos, units='dots')
lastFreq = freq
alpha = 1.0
if freq < 0:
alpha = 0.5
col = charToCol.get(char.upper(), "k")
text = ax.text(0, 0, char, transform=t, fontsize=50, color=col, family="monospace", alpha=alpha)
text.set_path_effects([Scale(1,freq)])
fig.canvas.draw()
ex = text.get_window_extent(fig.canvas.renderer)
t = transforms.offset_copy(text._transform, y=ex.height*freq, units='dots')
xPos += ex.width+charXDist
开发者ID:maximilianh,项目名称:crisporPaper,代码行数:43,代码来源:plotSeqLogo.py
示例17: add_axlabel
def add_axlabel(x, y, text, ax=None, dx=0, dy=0, ha='center', va='center', **kwargs):
"""A label to an axis with appropriate default font properies"""
if ax is None: ax = P.gca()
dict_check_defaults(kwargs,
color = cfgget('title_color'),
family = cfgget('title_font'),
size = cfgget('label_size'),
)
trans = offset_copy(ax.transAxes, x=dx, y=dy, fig=ax.get_figure(), units='points')
ax.text(x, y, text, transform=trans, ha=ha, va=va, **kwargs)
开发者ID:jfleroux,项目名称:vacumm,代码行数:10,代码来源:common.py
示例18: get_label_tran
def get_label_tran(self):
"return transformation for text labels"
from matplotlib.transforms import offset_copy
offset = self.get_config_section("pointLabelOffset")
return offset_copy(self.gca().transData, self.figure,
offset["x"], offset["y"],
units="points")
开发者ID:gizela,项目名称:gizela,代码行数:10,代码来源:FigureLayoutBase.py
示例19: rainbow_text
def rainbow_text(x, y, strings, colors, orientation='horizontal',
ax=None, **kwargs):
"""
Take a list of *strings* and *colors* and place them next to each
other, with text strings[i] being shown in colors[i].
Parameters
----------
x, y : float
Text position in data coordinates.
strings : list of str
The strings to draw.
colors : list of color
The colors to use.
orientation : {'horizontal', 'vertical'}
ax : Axes, optional
The Axes to draw into. If None, the current axes will be used.
**kwargs
All other keyword arguments are passed to plt.text(), so you can
set the font size, family, etc.
"""
if ax is None:
ax = plt.gca()
t = ax.transData
canvas = ax.figure.canvas
assert orientation in ['horizontal', 'vertical']
if orientation == 'vertical':
kwargs.update(rotation=90, verticalalignment='bottom')
for s, c in zip(strings, colors):
text = ax.text(x, y, s + " ", color=c, transform=t, **kwargs)
# Need to draw to update the text position.
text.draw(canvas.get_renderer())
ex = text.get_window_extent()
if orientation == 'horizontal':
t = transforms.offset_copy(
text.get_transform(), x=ex.width, units='dots')
else:
t = transforms.offset_copy(
text.get_transform(), y=ex.height, units='dots')
开发者ID:QuLogic,项目名称:matplotlib,代码行数:42,代码来源:rainbow_text.py
示例20: offset_xlabel
def offset_xlabel(label, axes, offset):
"""
Draws an xlabel that is at the given offset from the bottom of the
axis, regardless of the status of the tick labels.
(Normal xlabels adjust upwards if tick labels are removed)
"""
text = matplotlib.text.Text(.5, 0, label, horizontalalignment='center')
text.set_transform(transforms.offset_copy(
axes.transAxes, axes.figure, x=0, y=offset, units='points'
))
text.set_clip_on(False)
axes.add_artist(text)
开发者ID:Waino,项目名称:etframes,代码行数:12,代码来源:etframes.py
注:本文中的matplotlib.transforms.offset_copy函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论