当前位置: 首页>>代码示例>>Python>>正文


Python PatchCollection.set_alpha方法代码示例

本文整理汇总了Python中matplotlib.collections.PatchCollection.set_alpha方法的典型用法代码示例。如果您正苦于以下问题:Python PatchCollection.set_alpha方法的具体用法?Python PatchCollection.set_alpha怎么用?Python PatchCollection.set_alpha使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.collections.PatchCollection的用法示例。


在下文中一共展示了PatchCollection.set_alpha方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: data2fig

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def data2fig(data, X, options, legend_title, xlabel, ylabel=r'Reachability~$\reachability$'):
    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1, len(data.keys())))
    else:
        colors = options['color'](pylab.linspace(0, 1, len(data.keys())))
    fig = MyFig(options, figsize=(10, 8), xlabel=r'Sources~$\sources$', ylabel=ylabel, grid=False, aspect='auto', legend=True)
    for j, nhdp_ht in enumerate(sorted(data.keys())):
        d = data[nhdp_ht]
        try:
            mean_y = [scipy.mean(d[n]) for n in X]
        except KeyError:
            logging.warning('key \"%s\" not found, continuing...', nhdp_ht)
            continue
        confs_y = [confidence(d[n])[2] for n in X]
        poly = [conf2poly(X, list(numpy.array(mean_y)+numpy.array(confs_y)), list(numpy.array(mean_y)-numpy.array(confs_y)), color=colors[j])]
        patch_collection = PatchCollection(poly, match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)
        fig.ax.plot(X, mean_y, label='$%d$' % nhdp_ht, color=colors[j])
    fig.ax.set_xticks(X)
    fig.ax.set_xticklabels(['$%s$' % i for i in X])
    fig.ax.set_ylim(0,1)
    fig.legend_title = legend_title
    return fig
开发者ID:Dekue,项目名称:des-routing-algorithms,代码行数:27,代码来源:helpers.py

示例2: get_circles_for_scatter

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def get_circles_for_scatter(x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0):
    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    circles = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        circles[i] = patches.Circle( pt, radius=r )

    # make a collection of those circles    
    cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)
    
    return cc
开发者ID:alexlib,项目名称:FlyPlotLib,代码行数:36,代码来源:plot.py

示例3: draw

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def draw(options):
    files = [f for f in os.listdir(options['outdir']) if f.endswith('.data')]

    degrees = list()
    diameters = list()
    velocities = list()
    for f in files:
        fin = open(options['outdir']+'/'+f, 'r')
        ts = -1
        for line in fin:
            if line.startswith('#'):
                continue
            time, degree, diameter, velocity = [t.strip() for t in line.split(',')]
            time = int(time)
            assert(ts == time-1)
            ts = time
            try:
                degrees[time].append(float(degree))
                diameters[time].append(int(diameter))
                velocities[time].append(float(velocity))
            except IndexError:
                degrees.append([float(degree)])
                diameters.append([int(diameter)])
                velocities.append([float(velocity)])

    polies = list()
    times = range(len(degrees))
    times2 = times + times[::-1]

    degrees_conf_upper = [confidence(d)[0] for d in degrees]
    degrees_conf_lower = [confidence(d)[1] for d in degrees]
    polies.append(conf2poly(times, degrees_conf_upper, degrees_conf_lower, color='blue'))

    diameters_conf_upper = [confidence(d)[0] for d in diameters]
    diameters_conf_lower = [confidence(d)[1] for d in diameters]
    polies.append(conf2poly(times, diameters_conf_upper, diameters_conf_lower, color='blue'))

    velocities_conf_upper = [confidence(d)[0] for d in velocities]
    velocities_conf_lower = [confidence(d)[1] for d in velocities]
    polies.append(conf2poly(times, velocities_conf_upper, velocities_conf_lower, color='green'))

    velocities = [scipy.mean(d) for d in velocities]
    diameters = [scipy.mean(d) for d in diameters]
    degrees = [scipy.mean(d) for d in degrees]

    fig = MyFig(options, figsize=(10, 8), xlabel='Time [s]', ylabel='Metric', grid=False, legend=True, aspect='auto', legend_pos='upper right')

    patch_collection = PatchCollection(polies, match_original=True)
    patch_collection.set_alpha(0.3)
    patch_collection.set_linestyle('dashed')
    fig.ax.add_collection(patch_collection)

    fig.ax.plot(times, degrees, label='Mean degree', color='blue')
    fig.ax.plot(times, diameters, label='Diameter', color='red')
    fig.ax.plot(times, velocities, label='Mean velocity $[m/s]$', color='green')

    fig.ax.set_xlim(0, options['duration'])
    y_max = max(max(degrees), max(diameters), max(velocities))
    fig.ax.set_ylim(0, y_max+10)
    fig.save('metrics', fileformat='pdf')
开发者ID:Dekue,项目名称:des-routing-algorithms,代码行数:62,代码来源:random_waypoint.py

示例4: show_boxes

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def show_boxes(boxes,S=None,col='b',ecol='k',alpha=1, fig=None):
	if boxes.dim != 2:
		raise Exception("show_boxes: dimension must be 2")
	if S is None:
		S = range(boxes.size)

	patches = []
	for i in S:
		art = mpatches.Rectangle(boxes.corners[i],boxes.widths[i][0],boxes.widths[i][1])
		patches.append(art)
        
	if fig is not None:
		ax = fig.gca()
	else:
                fig = plt.figure()
		ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	collection.set_alpha(alpha)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	#plt.show()
        plt.draw()
        return fig
开发者ID:caosuomo,项目名称:rads,代码行数:28,代码来源:gfx.py

示例5: plot_trajectory_ellipse

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def plot_trajectory_ellipse(frame, varx="attr_VARX", vary="attr_VARY", covxy="attr_COVXY", opacity_factor=1):
    """
    Draw the trajectory and uncertainty ellipses around teach point.
    1) Scatter of points 
    2) Trajectory lines
    3) Ellipses 
    :param frame: Trajectory
    :param opacity_factor: all opacity values are multiplied by this. Useful when used to plot multiple Trajectories in
     an overlay plot.
    :return: axis
    """
    ellipses = []    
    segments = []
    start_point = None

    for i, pnt in frame.iterrows():  
        # The ellipse
        U, s, V = np.linalg.svd(np.array([[pnt[varx], pnt[covxy]], 
                                          [pnt[covxy], pnt[vary]]]), full_matrices=True)
        w, h = s**.5 
        theta = np.arctan(V[1][0]/V[0][0])   # == np.arccos(-V[0][0])              
        ellipse = {"xy":pnt[list(frame.geo_cols)].values, "width":w, "height":h, "angle":theta}
        ellipses.append(Ellipse(**ellipse))
        
        # The line segment
        x, y = pnt[list(frame.geo_cols)][:2]
        if start_point:           
            segments.append([start_point, (x, y)])
        start_point = (x, y)

    ax = plt.gca()
    ellipses = PatchCollection(ellipses)
    ellipses.set_facecolor('none')
    ellipses.set_color("green")
    ellipses.set_linewidth(2)
    ellipses.set_alpha(.4*opacity_factor)
    ax.add_collection(ellipses)

    frame.plot(kind="scatter", x=frame.geo_cols[0], y=frame.geo_cols[1], marker=".", ax=plt.gca(), alpha=opacity_factor)

    lines = LineCollection(segments)
    lines.set_color("gray")
    lines.set_linewidth(1)
    lines.set_alpha(.2*opacity_factor)
    ax.add_collection(lines)
    return ax
开发者ID:Hezi-Resheff,项目名称:trajectory-aa-move-ecol,代码行数:48,代码来源:simple_plots.py

示例6: _get_fpt_ell_collection

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
 def _get_fpt_ell_collection(dm, fpts, T_data, alpha, edgecolor):
     ell_patches = []
     for (x, y, a, c, d) in fpts:  # Manually Calculated sqrtm(inv(A))
         with catch_warnings():
             simplefilter("ignore")
             aIS = 1 / sqrt(a)
             cIS = (c / sqrt(a) - c / sqrt(d)) / (a - d + eps(1))
             dIS = 1 / sqrt(d)
         transEll = Affine2D([(aIS, 0, x), (cIS, dIS, y), (0, 0, 1)])
         unitCirc1 = Circle((0, 0), 1, transform=transEll)
         ell_patches = [unitCirc1] + ell_patches
     ellipse_collection = PatchCollection(ell_patches)
     ellipse_collection.set_facecolor("none")
     ellipse_collection.set_transform(T_data)
     ellipse_collection.set_alpha(alpha)
     ellipse_collection.set_edgecolor(edgecolor)
     return ellipse_collection
开发者ID:Erotemic,项目名称:hotspotter,代码行数:19,代码来源:DrawManager.py

示例7: get_ellipses_for_scatter

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def get_ellipses_for_scatter(ax, x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0):
    
    # get ellipse size to make it a circle given axes
    x0, y0 = ax.transAxes.transform((ax.get_ylim()[0],ax.get_xlim()[0]))
    x1, y1 = ax.transAxes.transform((ax.get_ylim()[1],ax.get_xlim()[1]))
    dx = x1-x0
    dy = y1-y0
    maxd = max(dx,dy)
    
    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    ellipses = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        width = r*2*maxd/dx
        height = r*2*maxd/dy
        ellipses[i] = patches.Ellipse( pt, width, height)

    # make a collection of those circles    
    cc = PatchCollection(ellipses, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)
    
    return cc
开发者ID:alexlib,项目名称:FlyPlotLib,代码行数:46,代码来源:plot.py

示例8: plot_site

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def plot_site(options):
    options['prefix'] = 'site'
    fig = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Probability $p_s$', ylabel=r'Reachability~$\reachability$', aspect='auto')
    fig_vs = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Fraction of Forwarded Packets~$\forwarded$', ylabel=r'Reachability~$\reachability$', aspect='auto')

    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1.0, 3))
    else:
        colors = fu_colormap()(pylab.linspace(0, 1.0, 3))
    nodes = 105

    axins = None
    if options['inset_loc'] >= 0:
        axins = zoomed_inset_axes(fig_vs.ax, options['inset_zoom'], loc=options['inset_loc'])
        axins.set_xlim(options['inset_xlim'])
        axins.set_ylim(options['inset_ylim'])
        axins.set_xticklabels([])
        axins.set_yticklabels([])
        mark_inset(fig_vs.ax, axins, loc1=2, loc2=3, fc="none", ec="0.5")

    for i, (name, label) in enumerate(names):
        data = parse_site_only(options['datapath'][0], name)
        rs = numpy.array([r for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']])
        fws = numpy.array([fw for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']])/(nodes-1)
        ps = numpy.array([p for p, r, std, conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)])
        yerr = numpy.array([conf for p,r,std,conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)])

        patch_collection = PatchCollection([conf2poly(ps, list(rs+yerr), list(rs-yerr), color=colors[i])], match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)

        fig.ax.plot(ps, rs, label=label, color=colors[i])
        fig_vs.ax.plot(fws, rs, label=label, color=colors[i])
        if axins:
            axins.plot(fws, rs, color=colors[i])

    fig.ax.set_ylim(0, options['limit'])
    fig.legend_title = 'Graph'
    fig.save('graphs')
    fig_vs.legend_title = 'Graph'
    fig_vs.ax.set_xlim(0,1)
    fig_vs.ax.set_ylim(0,1)
    fig_vs.save('vs_pb')
开发者ID:Dekue,项目名称:des-routing-algorithms,代码行数:46,代码来源:plot_simu.py

示例9: show_boxes

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def show_boxes(boxes, S=None, col="b", ecol="k", alpha=1):
    if boxes.dim != 2:
        raise Exception("show_boxes: dimension must be 2")
    if S is None:
        S = range(boxes.size)

    patches = []
    for i in S:
        art = mpatches.Rectangle(boxes.corners[i], boxes.widths[i][0], boxes.widths[i][1])
        patches.append(art)

    ax = plt.gca()
    ax.hold(True)
    collection = PatchCollection(patches)
    collection.set_facecolor(col)
    collection.set_edgecolor(ecol)
    collection.set_alpha(alpha)
    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    plt.show()
开发者ID:caja-matematica,项目名称:climate_attractors,代码行数:22,代码来源:gfx.py

示例10: show_box

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def show_box(b, col="b", ecol="k", alpha=1):
    patches = []

    # lower left corner at b[0], followed by width and height
    xy = b[0]
    width = np.absolute(b[0, 1] - b[0, 0])
    height = np.absolute(b[1, 1] - b[1, 0])
    art = mpatches.Rectangle(xy, width, height)
    # art = mpatches.Rectangle(b[0],b[1,0],b[1,1])
    patches.append(art)

    ax = plt.gca()
    ax.hold(True)
    collection = PatchCollection(patches)
    collection.set_facecolor(col)
    collection.set_edgecolor(ecol)
    collection.set_alpha(alpha)
    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    plt.show()
开发者ID:caja-matematica,项目名称:climate_attractors,代码行数:22,代码来源:gfx.py

示例11: plot_sparse_trajectory

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def plot_sparse_trajectory(trajectory, r=50, opacity_factor=1, plot_text=True,
                           num_col="segment_sparcify_n", min_static=100):
    """
    Plots a sparsified trajectory as circles with the number of points they represent as a number inside.
    :param trajectory: Trajectory object
    :param r: the radius of circles
    :param num_col: where to find the number to put in the circles
    :param min_static: minimum count to change color of circle
    :param plot_text: put the text with num of points in the circle?
    :return: ax
    """
    ax = plt.gca()
    trajectory.plot(kind="scatter", x=trajectory.geo_cols[0], y=trajectory.geo_cols[1], marker=".",
                    ax=plt.gca(), alpha=0.0*opacity_factor)

    circles = []
    segments = []
    start_point = None

    for i, pnt in trajectory.iterrows():
        circles.append(Circle(pnt[list(trajectory.geo_cols)].values, radius=r))

        if plot_text:
            plt.text(*pnt[list(trajectory.geo_cols)], s=str(int(pnt[num_col])), fontsize=12)

        x, y = pnt[list(trajectory.geo_cols)][:2]
        if start_point:
            segments.append([start_point, (x, y)])
        start_point = (x, y)

    circles = PatchCollection(circles)
    circles.set_facecolor(['none' if cnt < min_static else 'red' for cnt in trajectory[num_col].values])
    circles.set_alpha(.5*opacity_factor)
    ax.add_collection(circles)

    lines = LineCollection(segments)
    lines.set_color("gray")
    lines.set_alpha(.2*opacity_factor)
    ax.add_collection(lines)

    return ax
开发者ID:Hezi-Resheff,项目名称:trajectory-aa-move-ecol,代码行数:43,代码来源:simple_plots.py

示例12: show_box

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def show_box(b,col='b',ecol='k',alpha=1, fig=None):
	patches = []
	
	# lower left corner at b[0], followed by width and height
	art = mpatches.Rectangle(b[0],b[1,0],b[1,1])
	patches.append(art)

	if fig:
		ax = fig.gca()
	else:
                fig = plt.figure()
		ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	collection.set_alpha(alpha)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	plt.show()

	return fig
开发者ID:caosuomo,项目名称:rads,代码行数:24,代码来源:gfx.py

示例13: scatter

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def scatter(ax, x, y, color='black', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0, edgecolors='none'): 
    # color can be array-like, or a matplotlib color 
    # I can't figure out how to control alpha through the individual circle patches.. it seems to get overwritten by the collection. low priority!

    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    circles = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        circles[i] = patches.Circle( pt, radius=r )

    # make a collection of those circles    
    cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolors)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)

    # add collection to axis    
    ax.add_collection(cc)  
开发者ID:alexlib,项目名称:OdorPackets,代码行数:40,代码来源:floris_plot_lib.py

示例14: Polygon

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
  # a cor do polígono vem da imagem original            
  cores.append(image_rgb[y-1][x-1])
    
  # criamos um polígono para representar o triângulo (aqui começa o desenho
  # que estamos sintetizando)
  poly = Polygon(pontos[:,[0,1]][t_i], True)
  patches.append(poly)


# adicionamos os polígonos a uma coleção de colagens
p = PatchCollection(patches)
#print 'patches:', len(patches), 'regions:', len(cores)
# definimos as cores conforme imagem original  e as bordas em transparente
p.set_facecolor(cores)
p.set_edgecolor(cores)
p.set_alpha(.8)
# plotamos o desenho sintetizado
ax3.add_collection(p)
for ax in axes:
  ax.axis('off')

nome_pintura = '%s_passos.svg' % IMG[:-4]
fig.savefig(nome_pintura)

print 'pintura gerada em: %s' % nome_pintura 

# lista com coordenadas de cada triângulo
# print 'coords. triângulos:', coords_tri
# número de triângulos
# print 'num. de triângulos:', len(coords_tri)
开发者ID:automata,项目名称:tri-delaunay,代码行数:32,代码来源:tri_passos.py

示例15: plot_multiZ

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_alpha [as 别名]
def plot_multiZ(prefix, minval=0, maxval=200, bluefree=702):

    fraclist = np.array([0.005, 0.02, 0.2, 0.4, 1, 2.5])
    rw = 0.5
    rh = 0.05

    minchi = np.inf
    for z in range(fraclist.size):

        stepfile = "{}_Z{:04}_steps.dat".format(prefix, int(fraclist[z] * 1000))
        blueChi = np.loadtxt(stepfile, usecols=(17,), unpack=True)
        blueChi *= bluefree
        if blueChi[-1] < minchi:
            minchi = blueChi[-1]

    fig = plt.figure()
    grid = ImageGrid(
        fig, 111, nrows_ncols=(1, 1), cbar_mode="each", cbar_location="top", cbar_pad="1%", axes_class=None
    )
    ax = grid[0]

    ax.set_xlabel("$Z/Z_{\odot}$")
    ax.set_ylabel("MLWA")
    for z in range(fraclist.size):

        stepfile = "{}_Z{:04}_steps.dat".format(prefix, int(fraclist[z] * 1000))
        MLWA, TAUV, Chi, blueChi = np.loadtxt(stepfile, usecols=(12, 13, 15, 17), unpack=True)
        blueChi *= bluefree

        #        good = np.where(blueChi < 80)
        #        blueChi = blueChi[good]
        #        MLWA = MLWA[good]
        blueChi -= minchi
        patches = []
        print np.log10(blueChi.min()), np.log10(blueChi.max())
        for i in range(MLWA.size):
            #            patches.append(Circle((z,MLWA[i]),radius=0.1,linewidth=0))
            width = rw * ((minchi + 5000) / (blueChi[i] + 5000))
            #            width = rw * (minchi/blueChi[i])
            patches.append(Rectangle((z - width / 2, MLWA[i] - rh / 2), width, rh))

        collection = PatchCollection(
            np.array(patches)[::-1],
            cmap=plt.get_cmap("gnuplot"),
            norm=matplotlib.colors.Normalize(vmin=minval, vmax=maxval),
        )
        collection.set_alpha(0.1)
        collection.set_linewidth(0.0)
        collection.set_array(np.log10(blueChi)[::-1])
        ax.add_collection(collection)

        #        ax.axhline(y=MLWA[-1],color='k',ls=':',alpha=0.6)
        ax.hlines(MLWA[-1], z - 0.5, z + 0.5, color="g", lw=2)
        ax.text(
            z + 0.5,
            MLWA[-1],
            "{:5.2f}%, {:4.1f}".format(100 - 100 * ss.chi2.cdf(blueChi[-1], bluefree + 5), blueChi[-1]),
        )

    collection.set_alpha(1.0)
    cbar = ax.cax.colorbar(collection)

    ci = [68.27, 50.0, 80.0, 40.0]
    dc = [4.72, 3.36, 5.99, 2.75]

    # for (c, d) in zip(ci, dc):
    #     ax.cax.axvline(x = np.log10(d), color='g')
    #     ax.cax.text(np.log10(d) - 0.03, 2, '{}'.format(c),
    #                 transform=ax.cax.transData,
    #                 fontsize=8)

    collection.set_alpha(0.1)
    cbar.set_label_text("Log( $\Delta\chi^2_{\mathrm{blue}}$ )")

    ax.set_xlim(-1, fraclist.size + 1)
    ax.set_ylim(0, 12)
    ax.set_xticks(np.arange(fraclist.size))
    ax.set_xticklabels(fraclist)
    fig.show()

    return fig
开发者ID:eigenbrot,项目名称:snakes,代码行数:83,代码来源:plot_steps.py


注:本文中的matplotlib.collections.PatchCollection.set_alpha方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。