本文整理汇总了Python中matplotlib.pyplot.sci函数的典型用法代码示例。如果您正苦于以下问题:Python sci函数的具体用法?Python sci怎么用?Python sci使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sci函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: circles
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
if np.isscalar(c):
kwargs.setdefault('color', c)
c = None
if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc'))
if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec'))
if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls'))
if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw'))
patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)]
collection = PatchCollection(patches, **kwargs)
if c is not None:
collection.set_array(np.asarray(c))
collection.set_clim(vmin, vmax)
ax = plt.gca()
ax.add_collection(collection)
ax.autoscale_view()
if c is not None:
plt.sci(collection)
return collection
开发者ID:Gabs48,项目名称:SpringMassNetworks,代码行数:26,代码来源:utils.py
示例2: pltfactcamera
def pltfactcamera(*args, **kwargs):
ax = plt.gca()
fig = ax.get_figure()
fig.canvas.mpl_connect("pick_event", onpick)
ret = ax.factcamera(*args, **kwargs)
plt.draw_if_interactive()
plt.sci(ret)
return ret
开发者ID:dneise,项目名称:pyfact,代码行数:8,代码来源:__init__.py
示例3: contourf
def contourf(cube, *args, **kwargs):
"""
Draws filled contours based on the given Cube.
Kwargs:
* coords: list of :class:`~iris.coords.Coord` objects or coordinate names
Use the given coordinates as the axes for the plot. The order of the
given coordinates indicates which axis to use for each, where the first
element is the horizontal axis of the plot and the second element is
the vertical axis of the plot.
See :func:`matplotlib.pyplot.contourf` for details of other valid keyword
arguments.
"""
coords = kwargs.get('coords')
kwargs.setdefault('antialiased', True)
result = _draw_2d_from_points('contourf', None, cube, *args, **kwargs)
# Matplotlib produces visible seams between anti-aliased polygons.
# But if the polygons are virtually opaque then we can cover the seams
# by drawing anti-aliased lines *underneath* the polygon joins.
# Figure out the alpha level for the contour plot
if result.alpha is None:
alpha = result.collections[0].get_facecolor()[0][3]
else:
alpha = result.alpha
# If the contours are anti-aliased and mostly opaque then draw lines under
# the seams.
if result.antialiased and alpha > 0.95:
levels = result.levels
colors = [c[0] for c in result.tcolors]
if result.extend == 'neither':
levels = levels[1:-1]
colors = colors[:-1]
elif result.extend == 'min':
levels = levels[:-1]
colors = colors[:-1]
elif result.extend == 'max':
levels = levels[1:]
colors = colors[:-1]
else:
colors = colors[:-1]
if len(levels) > 0:
# Draw the lines just *below* the polygons to ensure we minimise
# any boundary shift.
zorder = result.collections[0].zorder - .1
contour(cube, levels=levels, colors=colors, antialiased=True,
zorder=zorder, coords=coords)
# Restore the current "image" to 'result' rather than the mappable
# resulting from the additional call to contour().
plt.sci(result)
return result
开发者ID:ckmo,项目名称:iris,代码行数:56,代码来源:plot.py
示例4: __set_current_image
def __set_current_image(ax, img):
'''Helper to set the current image in pyplot mode.
If the provided `ax` is not `None`, then we assume that the user is using the object API.
In this case, the pyplot current image is not set.
'''
if ax is None:
import matplotlib.pyplot as plt
plt.sci(img)
开发者ID:Monal415,项目名称:librosa,代码行数:10,代码来源:display.py
示例5: plot_grid
def plot_grid(grid: RegularGrid, ax: Axes=None, crs: CRS=None, band: Union[int, tuple]=-1, **kwargs):
""" Plot a grid instance
Parameters
----------
grid : RegularGrid
raster data to plot
ax : Axes, optional
Axes to plot to [default plt.gca()]
crs : CRS, optional
Currently not supported
band : int or tuple, optional
Band(s) to plot. If *grid* has three bands, by default the three are
plotted in false colour as RGB channels. Otherwise, the first band is
plotted by default. If *band* is a tuple, it must have three integer
elements.
Notes
-----
Additional arguments are passed to `matplotlib.pyplot.imshow`
"""
kwargs.setdefault("origin", "bottom")
kwargs.setdefault("extent", grid.get_extent(crs=crs))
kwargs.setdefault("cmap", cm.binary_r)
if crs is not None and crs != grid.crs:
raise NotImplementedError("RegularGrid reprojection not supported")
# compute the pixels that can actually be displayed
# be slightly generous by using a factor of 0.75 to avoid choosing too low
# of a resolution
_, _, width, height = ax.bbox.bounds
ny, nx = grid.size
r = (max(int(0.75*ny//height), 1), max(int(0.75*nx//width), 1))
if band == -1:
if len(grid.bands) == 3 and (band == -1):
band = (0, 1, 2)
else:
band = 0
if isinstance(band, int):
arr = grid[::r[0],::r[1],band]
arr = np.ma.masked_equal(arr, grid.nodata)
else:
if len(band) not in (3, 4):
raise ValueError("bands must be RGB or RGBA (length 3 or 4)")
arr = np.dstack([grid[::r[0],::r[1],i] for i in band]).astype(np.float32)
arr = np.ma.masked_equal(arr, grid.nodata)
arr[:,:,:3] /= arr[:,:,:3].max()
im = ax.imshow(arr, **kwargs)
if ax == gca():
sci(im)
return im
开发者ID:fortyninemaps,项目名称:karta-map,代码行数:53,代码来源:plotting.py
示例6: smooth_contourf
def smooth_contourf(*args,**kwargs):
kwargs['filled'] = True
ax=kwargs.pop('ax',pyp.gca())
washold = ax.ishold()
hold = kwargs.pop('hold', None)
if hold is not None:
ax.hold(hold)
try:
ret = SmoothContour(ax,*args,**kwargs)
pyp.draw_if_interactive()
finally:
ax.hold(washold)
if ret._A is not None: pyp.sci(ret)
return ret
开发者ID:CKrawczyk,项目名称:astroML,代码行数:14,代码来源:smooth_contour.py
示例7: plot_structure
def plot_structure(self, cmap='YlGnBu', site_radius=(0.03, 0.05), num_periods=1, **kwargs):
"""Plot the spatial structure with a colormap of :attr:`data` at the lattice sites
Both the site size and color are used to display the data.
Parameters
----------
cmap : str
Matplotlib colormap to be used for the data.
site_radius : Tuple[float, float]
Min and max radius of lattice sites. This range will be used to visually
represent the magnitude of the data.
num_periods : int
Number of times to repeat periodic boundaries.
"""
ax = plt.gca()
ax.set_aspect('equal', 'datalim')
ax.set_xlabel('x (nm)')
ax.set_ylabel('y (nm)')
def to_radii(data):
if not isinstance(site_radius, (tuple, list)):
return site_radius
positive_data = data - data.min()
maximum = positive_data.max()
if not np.allclose(maximum, 0):
delta = site_radius[1] - site_radius[0]
return site_radius[0] + delta * positive_data / maximum
else:
return site_radius[1]
props = structure_plot_properties(**kwargs)
props['site'] = with_defaults(props['site'], radius=to_radii(self.data), cmap=cmap)
collection = plot_sites(self.pos, self.data, **props['site'])
hop = self.hoppings.tocoo()
props['hopping'] = with_defaults(props['hopping'], colors='#bbbbbb')
plot_hoppings(self.pos, hop, **props['hopping'])
props['site']['alpha'] = props['hopping']['alpha'] = 0.5
plot_periodic_boundaries(self.pos, hop, self.boundaries, self.data, num_periods, **props)
pltutils.despine(trim=True)
pltutils.add_margin()
plt.sci(collection)
return collection
开发者ID:Yukee,项目名称:pybinding,代码行数:48,代码来源:results.py
示例8: plot
def plot(self, log = False, axes=None, **imshow_args):
#Get current axes
if not axes:
axes = plt.gca()
axes.set_title(self.__repr__())
axes.set_ylabel('pixels')
axes.set_xlabel('pixels')
if log:
ret = axes.imshow(self.data, cmap=plt.cm.Greys_r, norm = LogNorm())
else:
ret = axes.imshow(self.data, cmap=plt.cm.bone)
plt.colorbar(ret)
plt.sci(ret)
return ret
开发者ID:ayshih,项目名称:heroespy,代码行数:16,代码来源:sas.py
示例9: plot
def plot():
# Example from
# <http://matplotlib.org/examples/pylab_examples/line_collection2.html>
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
fig = plt.figure()
# In order to efficiently plot many lines in a single set of axes,
# Matplotlib has the ability to add the lines all at once. Here is a
# simple example showing how it is done.
N = 50
x = np.arange(N)
# Here are many sets of y to plot vs x
ys = [x + i for i in x]
# We need to set the plot limits, they will not autoscale
ax = plt.axes()
ax.set_xlim((np.amin(x), np.amax(x)))
ax.set_ylim((np.amin(np.amin(ys)), np.amax(np.amax(ys))))
# colors is sequence of rgba tuples
# linestyle is a string or dash tuple. Legal string values are
# solid|dashed|dashdot|dotted. The dash tuple is (offset,
# onoffseq)
# where onoffseq is an even length tuple of on and off ink in
# points.
# If linestyle is omitted, 'solid' is used
# See matplotlib.collections.LineCollection for more information
# Make a sequence of x,y pairs
line_segments = LineCollection(
[list(zip(x, y)) for y in ys],
linewidths=(0.5, 1, 1.5, 2),
linestyles='dashdot'
)
line_segments.set_array(x)
ax.add_collection(line_segments)
fig = plt.gcf()
axcb = fig.colorbar(line_segments)
axcb.set_label('Line Number')
ax.set_title('Line Collection with mapped colors')
plt.sci(line_segments) # This allows interactive changing of the colormap.
return fig
开发者ID:awehrfritz,项目名称:matplotlib2tikz,代码行数:47,代码来源:test_line_collection.py
示例10: lines
def lines(xy, c='b', vmin=None, vmax=None, **kwargs):
"""
xy : sequence of array
Coordinates of points in lines.
`xy` is a sequence of array (line0, line1, ..., lineN) where
line = [(x0, y0), (x1, y1), ... (xm, ym)]
c : color or sequence of color, optional, default : 'b'
`c` can be a single color format string, or a sequence of color
specifications of length `N`, or a sequence of `N` numbers to be
mapped to colors using the `cmap` and `norm` specified via kwargs.
Note that `c` should not be a single numeric RGB or RGBA sequence
because that is indistinguishable from an array of values
to be colormapped. (If you insist, use `color` instead.)
`c` can be a 2-D array in which the rows are RGB or RGBA, however.
vmin, vmax : scalar, optional, default: None
`vmin` and `vmax` are used in conjunction with `norm` to normalize
luminance data. If either are `None`, the min and max of the
color array is used.
kwargs : `~matplotlib.collections.Collection` properties
Eg. alpha, linewidth(lw), linestyle(ls), norm, cmap, transform, etc.
Returns
-------
collection : `~matplotlib.collections.LineCollection`
"""
if np.isscalar(c):
kwargs.setdefault('color', c)
c = None
if 'ls' in kwargs:
kwargs.setdefault('linestyle', kwargs.pop('ls'))
if 'lw' in kwargs:
kwargs.setdefault('linewidth', kwargs.pop('lw'))
collection = LineCollection(xy, **kwargs)
if c is not None:
collection.set_array(np.asarray(c))
collection.set_clim(vmin, vmax)
ax = plt.gca()
ax.add_collection(collection)
ax.autoscale_view()
plt.draw_if_interactive()
if c is not None:
plt.sci(collection)
return collection
开发者ID:syrte,项目名称:handy,代码行数:46,代码来源:scatter.py
示例11: draw_specgram
def draw_specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128, cmap=None, xextent=None,
pad_to=None, sides='default', scale_by_freq=None, hold=None,
**kwargs):
ax = pyplot.gca()
# allow callers to override the hold state by passing hold=True|False
washold = ax.ishold()
if hold is not None:
ax.hold(hold)
try:
ret = specgram1(x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend,
window=window, noverlap=noverlap, cmap=cmap,
xextent=xextent, pad_to=pad_to, sides=sides,
scale_by_freq=scale_by_freq, **kwargs)
pyplot.draw_if_interactive()
finally:
ax.hold(washold)
pyplot.sci(ret[-1])
return ret
开发者ID:motobiker2008,项目名称:aotm,代码行数:21,代码来源:freq_spectr.py
示例12: quiver
def quiver(*args, **kw):
ax = gca()
# allow callers to override the hold state by passing hold=True|False
washold = ax.ishold()
hold = kw.pop("hold", None)
if hold is not None:
ax.hold(hold)
try:
if not ax._hold:
ax.cla()
q = Quiver(ax, *args, **kw)
ax.add_collection(q, autolim=True)
ax.autoscale_view()
draw_if_interactive()
finally:
ax.hold(washold)
sci(q)
return q
开发者ID:treverhines,项目名称:MyPlot,代码行数:22,代码来源:quiver.py
示例13: circles
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
"""
Make a scatter of circles plot of x vs y, where x and y are sequence
like objects of the same lengths. The size of circles are in data scale.
Parameters
----------
x,y : scalar or array_like, shape (n, )
Input data
s : scalar or array_like, shape (n, )
Radius of circle in data unit.
c : color or sequence of color, optional, default : 'b'
`c` can be a single color format string, or a sequence of color
specifications of length `N`, or a sequence of `N` numbers to be
mapped to colors using the `cmap` and `norm` specified via kwargs.
Note that `c` should not be a single numeric RGB or RGBA sequence
because that is indistinguishable from an array of values
to be colormapped. (If you insist, use `color` instead.)
`c` can be a 2-D array in which the rows are RGB or RGBA, however.
vmin, vmax : scalar, optional, default: None
`vmin` and `vmax` are used in conjunction with `norm` to normalize
luminance data. If either are `None`, the min and max of the
color array is used.
kwargs : `~matplotlib.collections.Collection` properties
Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls),
norm, cmap, transform, etc.
Returns
-------
paths : `~matplotlib.collections.PathCollection`
Examples
--------
a = np.arange(11)
circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')
plt.colorbar()
License
--------
This code is under [The BSD 3-Clause License]
(http://opensource.org/licenses/BSD-3-Clause)
"""
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
if np.isscalar(c):
kwargs.setdefault('color', c)
c = None
if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc'))
if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec'))
if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls'))
if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw'))
patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)]
collection = PatchCollection(patches, **kwargs)
if c is not None:
collection.set_array(np.asarray(c))
collection.set_clim(vmin, vmax)
ax = plt.gca()
ax.add_collection(collection)
ax.autoscale_view()
if c is not None:
plt.sci(collection)
return collection
开发者ID:cdavis1491,项目名称:flyby_repo,代码行数:62,代码来源:make_flyby_gif_w_MLratio.py
示例14: plot
def plot(data, mesh, shade_pml=False, axis=None, ticks=True, update=None, slice3d=(0,0,0), **kwargs):
""" Assumes that data has no ghost padding."""
data.shape = -1,1
sh_bc = mesh.shape(include_bc=True)
sh_primary = mesh.shape()
if data.shape == sh_bc:
has_bc = True
plot_shape = mesh.shape(include_bc=True, as_grid=True)
elif data.shape == sh_primary:
has_bc = False
plot_shape = mesh.shape(as_grid=True)
else:
raise ValueError('Shape mismatch between domain and data.')
if axis is None:
ax = plt.gca()
else:
ax = axis
data = data.reshape(plot_shape)
if mesh.dim == 1:
if update is None:
zs, = mesh.mesh_coords()
ret, = ax.plot(zs,data)
if has_bc:
ax.axvline(mesh.domain.parameters['z']['lbound'], color='r')
ax.axvline(mesh.domain.parameters['z']['rbound'], color='r')
else:
update.set_ydata(data)
ret = update
if mesh.dim == 2:
data = data.T
if update is None:
im = ax.imshow(data, interpolation='nearest', aspect='auto', **kwargs)
if ticks:
mesh_tickers(mesh)
else:
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
if has_bc:
draw_pml(mesh, 'x', 'LR', shade_pml=shade_pml)
draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml)
else:
update.set_data(data)
im = update
# Update current image for the colorbar
plt.sci(im)
ret = im
if mesh.dim == 3:
if update is None:
# X-Y plot
ax = plt.subplot(2,2,1)
imslice = int(slice3d[2]) # z slice
pltdata = data[:,:,imslice:(imslice+1)].squeeze()
imxy = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs)
if ticks:
mesh_tickers(mesh, ('y', 'x'))
else:
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
if has_bc:
draw_pml(mesh, 'y', 'LR', shade_pml=shade_pml)
draw_pml(mesh, 'x', 'TB', shade_pml=shade_pml)
# X-Z plot
ax = plt.subplot(2,2,2)
imslice = int(slice3d[1]) # y slice
pltdata = data[:,imslice:(imslice+1),:].squeeze().T
imxz = ax.imshow(pltdata, interpolation='nearest', aspect='equal', **kwargs)
if ticks:
mesh_tickers(mesh, ('x', 'z'))
else:
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
if has_bc:
draw_pml(mesh, 'x', 'LR', shade_pml=shade_pml)
draw_pml(mesh, 'z', 'TB', shade_pml=shade_pml)
# Y-Z plot
ax = plt.subplot(2,2,3)
imslice = int(slice3d[0]) # x slice
#.........这里部分代码省略.........
开发者ID:Forgotten,项目名称:pysit,代码行数:101,代码来源:vis.py
示例15: enumerate
norm = colors.Normalize(vmin=vmin, vmax=vmax)
for i, im in enumerate(images):
im.set_norm(norm)
if i > 0:
images[0].callbacksSM.connect('changed', ImageFollower(im))
#**************
# Colorbar
#**************
## The colorbar is also based on this master image.
#cax = fig.add_axes([0.82, 0.25, 0.025, 0.5])
#fig.colorbar(images[0], cax, orientation='vertical')
# We need the following only if we want to run this interactively and
# modify the colormap:
axes(ax[0]) # Return the current axes to the first one,
sci(images[0]) # because the current image must be in current axes.
#**************
# save fig
#**************
path_out = '../fig'
if not os.path.exists(path_out):
os.makedirs(path_out)
plt.savefig(path_out + '/' + dat_type + '_s' + str(sn) + '_rec_slice' + str(rec_y) + '.png',figsize=(8,4),dpi=300)
show()
开发者ID:DmBorisov,项目名称:2016_CIG_SPECFEM3D,代码行数:30,代码来源:plot_shot_gather.py
示例16: min
node_color_map=cm.get_cmap('gist_yarg')
edge_color_map=cm.get_cmap('jet')
nx.draw(G,pos=pos_vals, alpha=0.07, with_labels=False)
nx.draw_networkx_nodes(sample, pos_vals, nodelist=sample.graph['source_nodes'], alpha=0.7, node_shape='s', node_size=600, node_color='chocolate')
nx.draw_networkx_nodes(sample, pos_vals, nodelist=sample.graph['destination_nodes'],alpha=0.7, node_shape='s', node_size=600, node_color='#87CEFA')
nodes=nx.draw_networkx_nodes(sample, pos_vals, nodelist=sample.nodes(), node_color=n_color, cmap=node_color_map, vmin=min(n_color), vmax=max(n_color))
edges=nx.draw_networkx_edges(G, pos_vals, edgelist=sample.edges(),width=2, edge_color=e_color, edge_cmap=edge_color_map, edge_vmin=min(e_color),edge_vmax=max(e_color))
for n in sample.nodes():
x,y=pos_vals[n]
plt.text(x,y-0.005,s=str(n)+'-'+str(sample.node[n]['times_selected']),horizontalalignment='center', fontdict={'color' : 'darkred','weight' : 'bold', 'size' : 12})
if min(n_color) != max(n_color):
plt.sci(nodes)
res=np.linspace(min(n_color), max(n_color), 10)
cb=plt.colorbar(shrink=.7)
print len(res) , res[1], res[0]
if max(n_color)-min(n_color)< 10 or res[1]-res[0]< 1:
cb.locator=MultipleLocator(1)
cb.update_ticks()
cb.set_label("Node degree")
if min(e_color) != max(e_color):
plt.sci(edges)
res=np.linspace(min(e_color), max(e_color), 10)
cb=plt.colorbar(orientation='horizontal' , shrink=.7)
if max(e_color)-min(e_color)< 10 or res[1]-res[0]< 1:
cb.locator=MultipleLocator(1)
cb.update_ticks()
开发者ID:emrahcem,项目名称:cons-python,代码行数:31,代码来源:km_path_sampler.py
示例17: voltPlot
def voltPlot(tree, workDir=None, neatoLayout=False):
''' Draw a color-coded map of the voltage drop on a feeder.
Returns a matplotlib object. '''
# Get rid of schedules and climate:
for key in tree.keys():
if tree[key].get("argument","") == "\"schedules.glm\"" or tree[key].get("tmyfile","") != "":
del tree[key]
# Make sure we have a voltDump:
def safeInt(x):
try: return int(x)
except: return 0
biggestKey = max([safeInt(x) for x in tree.keys()])
tree[str(biggestKey*10)] = {"object":"voltdump","filename":"voltDump.csv"}
# Run Gridlab.
if not workDir:
workDir = tempfile.mkdtemp()
print "gridlabD runInFilesystem with no specified workDir. Working in", workDir
gridlabOut = gridlabd.runInFilesystem(tree, attachments=[], workDir=workDir)
with open(pJoin(workDir,'voltDump.csv'),'r') as dumpFile:
reader = csv.reader(dumpFile)
reader.next() # Burn the header.
keys = reader.next()
voltTable = []
for row in reader:
rowDict = {}
for pos,key in enumerate(keys):
rowDict[key] = row[pos]
voltTable.append(rowDict)
# Calculate average node voltage deviation. First, helper functions.
def pythag(x,y):
''' For right triangle with sides a and b, return the hypotenuse. '''
return math.sqrt(x**2+y**2)
def digits(x):
''' Returns number of digits before the decimal in the float x. '''
return math.ceil(math.log10(x+1))
def avg(l):
''' Average of a list of ints or floats. '''
return sum(l)/len(l)
# Detect the feeder nominal voltage:
for key in tree:
ob = tree[key]
if type(ob)==dict and ob.get('bustype','')=='SWING':
feedVoltage = float(ob.get('nominal_voltage',1))
# Tot it all up.
nodeVolts = {}
for row in voltTable:
allVolts = []
for phase in ['A','B','C']:
phaseVolt = pythag(float(row['volt'+phase+'_real']),
float(row['volt'+phase+'_imag']))
if phaseVolt != 0.0:
if digits(phaseVolt)>3:
# Normalize to 120 V standard
phaseVolt = phaseVolt*(120/feedVoltage)
allVolts.append(phaseVolt)
nodeVolts[row.get('node_name','')] = avg(allVolts)
# Color nodes by VOLTAGE.
fGraph = feeder.treeToNxGraph(tree)
voltChart = plt.figure(figsize=(10,10))
plt.axes(frameon = 0)
plt.axis('off')
if neatoLayout:
# HACK: work on a new graph without attributes because graphViz tries to read attrs.
cleanG = nx.Graph(fGraph.edges())
cleanG.add_nodes_from(fGraph)
positions = nx.graphviz_layout(cleanG, prog='neato')
else:
positions = {n:fGraph.node[n].get('pos',(0,0)) for n in fGraph}
edgeIm = nx.draw_networkx_edges(fGraph, positions)
nodeIm = nx.draw_networkx_nodes(fGraph,
pos = positions,
node_color = [nodeVolts.get(n,0) for n in fGraph.nodes()],
linewidths = 0,
node_size = 30,
cmap = plt.cm.jet)
plt.sci(nodeIm)
plt.clim(110,130)
plt.colorbar()
return voltChart
开发者ID:acmbc68,项目名称:omf,代码行数:79,代码来源:voltageDrop.py
示例18: is
# simple example showing how it is done.
N = 50
x = np.arange(N)
# Here are many sets of y to plot vs x
ys = [x + i for i in x]
# We need to set the plot limits, they will not autoscale
fig, ax = plt.subplots()
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(ys), np.max(ys))
# colors is sequence of rgba tuples
# linestyle is a string or dash tuple. Legal string values are
# solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq)
# where onoffseq is an even length tuple of on and off ink in points.
# If linestyle is omitted, 'solid' is used
# See :class:`matplotlib.collections.LineCollection` for more information
# Make a sequence of x,y pairs
line_segments = LineCollection([np.column_stack([x, y]) for y in ys],
linewidths=(0.5, 1, 1.5, 2),
linestyles='solid')
line_segments.set_array(x)
ax.add_collection(line_segments)
axcb = fig.colorbar(line_segments)
axcb.set_label('Line Number')
ax.set_title('Line Collection with mapped colors')
plt.sci(line_segments) # This allows interactive changing of the colormap.
plt.show()
开发者ID:adnanb59,项目名称:matplotlib,代码行数:30,代码来源:line_collection.py
示例19: plot
def plot(self, axes=None, gamma=None, annotate=True, # pylint: disable=W0613
title="SunPy Composite Plot", **matplot_args):
"""Plots the composite map object using matplotlib
Parameters
----------
axes: matplotlib.axes object or None
If provided the image will be plotted on the given axes. Else the
current matplotlib axes will be used.
gamma : float
Gamma value to use for the color map
annotate : bool
If true, the data is plotted at it's natural scale; with
title and axis labels.
**matplot_args : dict
Matplotlib Any additional imshow arguments that should be used
when plotting the image.
Returns
-------
ret : List
List of axes image or quad contour sets that have been plotted.
"""
#Get current axes
if not axes:
axes = plt.gca()
if annotate:
# x-axis label
if self._maps[0].coordinate_system['x'] == 'HG':
xlabel = 'Longitude [%s]' % self._maps[0].units['x']
else:
xlabel = 'X-position [%s]' % self._maps[0].units['x']
# y-axis label
if self._maps[0].coordinate_system['y'] == 'HG':
ylabel = 'Latitude [%s]' % self._maps[0].units['y']
else:
ylabel = 'Y-position [%s]' % self._maps[0].units['y']
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_title(title)
#Define a list of plotted objects
ret = []
# Plot layers of composite map
for m in self._maps:
# Parameters for plotting
params = {
"origin": "lower",
"extent": m.xrange + m.yrange,
"cmap": m.cmap,
"norm": m.norm(),
"alpha": m.alpha,
"zorder": m.zorder,
}
params.update(matplot_args)
if m.levels is False:
ret.append(axes.imshow(m, **params))
# Use contour for contour data, and imshow otherwise
if m.levels is not False:
# Set data with values <= 0 to transparent
# contour_data = np.ma.masked_array(m, mask=(m <= 0))
ret.append(axes.contour(m, m.levels, **params))
#Set the label of the first line so a legend can be created
ret[-1].collections[0].set_label(m.name)
# Adjust axes extents to include all data
axes.axis('image')
#Set current image (makes colorbar work)
plt.sci(ret[0])
return ret
开发者ID:ToyDragon,项目名称:sunpy,代码行数:81,代码来源:compositemap.py
示例20: plot
def plot(self, gamma=None, annotate=True, axes=None, **imshow_args):
""" Plots the map object using matplotlib, in a method equivalent
to plt.imshow() using nearest neighbour interpolation.
Parameters
----------
gamma : float
Gamma value to use for the color map
annotate : bool
If true, the data is plotted at it's natural scale; with
title and axis labels.
axes: matplotlib.axes object or None
If provided the image will be plotted on the given axes. Else the
current matplotlib axes will be used.
**imshow_args : dict
Any additional imshow arguments that should be used
when plotting the image.
Examples
--------
#Simple Plot with color bar
plt.figure()
aiamap.plot()
plt.colorbar()
#Add a limb line and grid
aia.plot()
aia.draw_limb()
aia.draw_grid()
"""
# Check that the image is properly oriented
if not np.array_equal(self.rotation_matrix, np.matrix(np.identity(2))):
warnings.warn("This map is not properly oriented. Plot axes may be incorrect",
Warning)
#Get current axes
if not axes:
axes = plt.gca()
# Normal plot
if annotate:
axes.set_title("{name} {date:{tmf}}".format(name=self.name,
date=parse_time(self.date),
tmf=TIME_FORMAT))
# x-axis label
if self.coordinate_system['x'] == 'HG':
xlabel = 'Longitude [{lon}]'.format(lon=self.units['x'])
else:
xlabel = 'X-position [{xpos}]'.format(xpos=self.units['x'])
# y-axis label
if self.coordinate_system['y'] == 'HG':
ylabel = 'Latitude [{lat}]'.format(lat=self.units['y'])
else:
ylabel = 'Y-position [{ypos}]'.format(ypos=self.units['y'])
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
# Determine extent
extent = self.xrange + self.yrange
cmap = deepcopy(self.cmap)
if gamma is not None:
cmap.set_gamma(gamma)
# make imshow kwargs a dict
kwargs = {'origin':'lower',
'cmap':cmap,
'norm':self.mpl_color_normalizer,
'extent':extent,
'interpolation':'nearest'}
kwargs.update(imshow_args)
ret = axes.imshow(self.data, **kwargs)
#Set current image (makes colorbar work)
plt.sci(ret)
return ret
开发者ID:amhuertash,项目名称:sunpy,代码行数:82,代码来源:mapbase.py
注:本文中的matplotlib.pyplot.sci函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论