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


Python Figure.set_alpha方法代码示例

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


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

示例1: tricontouring_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def tricontouring_response(tri_subset, data, request, dpi=None):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """

    dpi = dpi or 80.

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']
    nlvls = request.GET['numcontours']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    tri_subset.x, tri_subset.y = pyproj.transform(EPSG4326, crs, tri_subset.x, tri_subset.y)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin is not None and cmax is not None:
        lvls = np.linspace(cmin, cmax, nlvls)
        norm = norm_func(vmin=cmin, vmax=cmax, clip=True)
    else:
        lvls = nlvls
        norm = norm_func()

    if request.GET['image_type'] == 'filledcontours':
        ax.tricontourf(tri_subset, data, lvls, norm=norm, cmap=colormap, extend='both')
    elif request.GET['image_type'] == 'contours':
        ax.tricontour(tri_subset, data, lvls, norm=norm, cmap=colormap, extend='both')

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:brianmckenna,项目名称:sci-wms,代码行数:62,代码来源:mpl_handler.py

示例2: quiver_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def quiver_response(lon, lat, dx, dy, request, dpi=None):

    dpi = dpi or 80.

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    vectorscale = request.GET['vectorscale']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']
    unit_vectors = None  # We don't support requesting these yet, but wouldn't be hard

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)  # TODO order for non-inverse?

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    mags = np.sqrt(dx**2 + dy**2)

    cmap = mpl.cm.get_cmap(colormap)

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin is not None and cmax is not None:
        mags[mags > cmax] = cmax
        mags[mags < cmin] = cmin
        norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        norm = norm_func()

    # plot unit vectors
    if unit_vectors:
        ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=cmap, norm=norm, scale=vectorscale)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm, scale=vectorscale)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:ocefpaf,项目名称:sci-wms,代码行数:62,代码来源:mpl_handler.py

示例3: quiver_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def quiver_response(lon,
                    lat,
                    dx,
                    dy,
                    request,
                    vectorscale,
                    unit_vectors=False,
                    dpi=80):

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)  # TODO order for non-inverse?

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    mags = np.sqrt(dx**2 + dy**2)

    cmap = mpl.cm.get_cmap(colormap)
    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    norm = None
    if cmin is not None and cmax is not None:
        mags[mags > cmax] = cmax
        mags[mags < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

    # plot unit vectors
    if unit_vectors:
        ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=cmap, scale=vectorscale)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm, scale=vectorscale)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:ayan-usgs,项目名称:sci-wms,代码行数:59,代码来源:mpl_handler.py

示例4: contouring_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def contouring_response(lon, lat, data, request, dpi=None):

    dpi = dpi or 80.

    bbox, width, height, colormap, cmin, cmax, crs = _get_common_params(request)
    nlvls = request.GET['numcontours']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    if cmin is not None and cmax is not None:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        lvls = np.linspace(cmin, cmax, nlvls)
        norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        lvls = nlvls
        norm = norm_func()

    if request.GET['image_type'] == 'filledcontours':
        ax.contourf(x, y, data, lvls, norm=norm, cmap=colormap)
    elif request.GET['image_type'] == 'contours':
        ax.contour(x, y, data, lvls, norm=norm, cmap=colormap)
    elif request.GET['image_type'] == 'filledhatches':
        hatches = DEFAULT_HATCHES[:lvls]
        ax.contourf(x, y, data, lvls, norm=norm, cmap=colormap, hatches=hatches)
    elif request.GET['image_type'] == 'hatches':
        hatches = DEFAULT_HATCHES[:lvls]
        ax.contourf(x, y, data, lvls, norm=norm, colors='none', hatches=hatches)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:ocefpaf,项目名称:sci-wms,代码行数:55,代码来源:mpl_handler.py

示例5: tricontourf_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def tricontourf_response(tri_subset,
                         data,
                         request,
                         dpi=80.0,
                         nlvls=15):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """
    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    tri_subset.x, tri_subset.y = pyproj.transform(EPSG4326, crs, tri_subset.x, tri_subset.y)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        lvls = np.linspace(float(cmin), float(cmax), int(nlvls))
        ax.tricontourf(tri_subset, data, levels=lvls, cmap=colormap)
    else:
        ax.tricontourf(tri_subset, data, cmap=colormap)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:ayan-usgs,项目名称:sci-wms,代码行数:53,代码来源:mpl_handler.py

示例6: contourf_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def contourf_response(lon,
                      lat,
                      data,
                      request,
                      dpi=80,
                      nlvls = 15):

    xmin, ymin, xmax, ymax = wms_handler.get_bbox(request)

    width, height = wms_handler.get_width_height(request)

    colormap = wms_handler.get_colormap(request)

    cmin, cmax = wms_handler.get_climits(request)

    #proj = get_pyproj(request)
    #xcrs, ycrs = proj(lon.flatten(),lat.flatten())
    CRS = get_pyproj(request)
    xcrs, ycrs = pyproj.transform(EPSG4326, CRS, lon.flatten(),lat.flatten()) #TODO order for non-inverse?
    #logger.info("xcrs, ycrs: {0} {1}".format(xcrs, ycrs))

    xcrs = xcrs.reshape(data.shape)
    ycrs = ycrs.reshape(data.shape)

    sxcrs = np.argsort(xcrs[1,:])
    sycrs = np.argsort(ycrs[:,1])

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    lvls = np.linspace(cmin, cmax, nlvls)

    #ax.contourf(xcrs, ycrs, data, levels=lvls, cmap=colormap)
    ax.contourf(xcrs[sycrs,:][:,sxcrs], ycrs[sycrs,:][:,sxcrs], data[sycrs,:][:,sxcrs], levels=lvls, cmap=colormap)

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0, 0, 1, 1])
    
    canvas = FigureCanvasAgg(fig)
    
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)

    return response
开发者ID:brianmckenna,项目名称:sci-wms_OLD,代码行数:52,代码来源:matplotlib_handler.py

示例7: create_projected_fig

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def create_projected_fig(lonmin, latmin, lonmax, latmax, projection, height, width):
    from mpl_toolkits.basemap import Basemap
    from matplotlib.figure import Figure
    fig = Figure(dpi=80, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height)
    fig.set_figwidth(width)
    m = Basemap(llcrnrlon=lonmin, llcrnrlat=latmin,
            urcrnrlon=lonmax, urcrnrlat=latmax, projection=projection,
            resolution=None,
            lat_ts = 0.0,
            suppress_ticks=True)
    m.ax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[])
    return fig, m
开发者ID:dstuebe,项目名称:sci-wms,代码行数:16,代码来源:ugrid.py

示例8: blank_canvas

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def blank_canvas(width, height, dpi=5):
    """
    return a transparent (blank) response
    used for tiles with no intersection with the current view or for some other error.
    """
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    ax = fig.add_axes([0, 0, 1, 1])
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0, 0, 1, 1])
    canvas = FigureCanvasAgg(fig)
    return canvas
开发者ID:jdickin,项目名称:sci-wms,代码行数:17,代码来源:data_handler.py

示例9: pcolormesh_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def pcolormesh_response(lon,
                        lat,
                        data,
                        request,
                        dpi=80):
    bbox, width, height, colormap, cmin, cmax, crs = _get_common_params(request)

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        norm = norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        norm = norm_func()

    masked = np.ma.masked_invalid(data)
    ax.pcolormesh(x, y, masked, norm=norm, cmap=colormap)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:rsignell-usgs,项目名称:sci-wms,代码行数:42,代码来源:mpl_handler.py

示例10: pcolormesh_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def pcolormesh_response(lon,
                        lat,
                        data,
                        request,
                        dpi=80):
    params = _get_common_params(request)
    bbox, width, height, colormap, cmin, cmax, crs = params

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    cmap = mpl.cm.get_cmap(colormap)

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        bounds = np.linspace(cmin, cmax, 15)
    else:
        norm = None
    masked = np.ma.masked_invalid(data)
    ax.pcolormesh(x, y, masked, vmin=5, vmax=30, norm=norm)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:ayan-usgs,项目名称:sci-wms,代码行数:40,代码来源:mpl_handler.py

示例11: getLegendGraphic

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def getLegendGraphic(request, dataset):
    """
    Parse parameters from request that looks like this:

    http://webserver.smast.umassd.edu:8000/wms/NecofsWave?
    ELEVATION=1
    &LAYERS=hs
    &TRANSPARENT=TRUE
    &STYLES=facets_average_jet_0_0.5_node_False
    &SERVICE=WMS
    &VERSION=1.1.1
    &REQUEST=GetLegendGraphic
    &FORMAT=image%2Fpng
    &TIME=2012-06-20T18%3A00%3A00
    &SRS=EPSG%3A3857
    &LAYER=hs
    """
    styles = request.GET["styles"].split("_")
    try:
        climits = (float(styles[3]), float(styles[4]))
    except:
        climits = (None, None)
    variables = request.GET["layer"].split(",")
    plot_type = styles[0]
    colormap = styles[2].replace('-', '_')

    # direct the service to the dataset
    # make changes to server_local_config.py
    if settings.LOCALDATASET:
        url = settings.LOCALDATASETPATH[dataset]
    else:
        url = Dataset.objects.get(name=dataset).path()
    nc = netCDF4.Dataset(url)

    """
    Create figure and axes for small legend image
    """
    #from matplotlib.figure import Figure
    from matplotlib.pylab import get_cmap
    fig = Figure(dpi=100., facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figwidth(1*1.3)
    fig.set_figheight(1.5*1.3)

    """
    Create the colorbar or legend and add to axis
    """
    v = cf.get_by_standard_name(nc, variables[0])

    try:
        units = v.units
    except:
        units = ''
    # vertical level label
    if v.ndim > 3:
        units = units + '\nvertical level: %s' % _get_vertical_level(nc, v)
    if climits[0] is None or climits[1] is None:  # TODO: NOT SUPPORTED RESPONSE
            #going to have to get the data here to figure out bounds
            #need elevation, bbox, time, magnitudebool
            CNorm = None
            ax = fig.add_axes([0, 0, 1, 1])
            ax.grid(False)
            ax.text(.5, .5, 'Error: No Legend\navailable for\nautoscaled\ncolor styles!', ha='center', va='center', transform=ax.transAxes, fontsize=8)
    elif plot_type not in ["contours", "filledcontours"]:
        #use limits described by the style
        ax = fig.add_axes([.01, .05, .2, .8])  # xticks=[], yticks=[])
        CNorm = matplotlib.colors.Normalize(vmin=climits[0],
                                            vmax=climits[1],
                                            clip=False,
                                            )
        cb = matplotlib.colorbar.ColorbarBase(ax,
                                              cmap=get_cmap(colormap),
                                              norm=CNorm,
                                              orientation='vertical',
                                              )
        cb.set_label(units, size=8)

    else:  # plot type somekind of contour
        if plot_type == "contours":
            #this should perhaps be a legend...
            #ax = fig.add_axes([0,0,1,1])
            fig_proxy = Figure(frameon=False, facecolor='none', edgecolor='none')
            ax_proxy = fig_proxy.add_axes([0, 0, 1, 1])
            CNorm = matplotlib.colors.Normalize(vmin=climits[0], vmax=climits[1], clip=True)
            #levs = numpy.arange(0, 12)*(climits[1]-climits[0])/10
            levs = numpy.linspace(climits[0], climits[1], 11)
            x, y = numpy.meshgrid(numpy.arange(10), numpy.arange(10))
            cs = ax_proxy.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(colormap))

            proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

            fig.legend(proxy, levs,
                       #bbox_to_anchor = (0, 0, 1, 1),
                       #bbox_transform = fig.transFigure,
                       loc = 6,
                       title = units,
                       prop = { 'size' : 8 },
                       frameon = False,
                       )
        elif plot_type == "filledcontours":
#.........这里部分代码省略.........
开发者ID:brianmckenna,项目名称:sci-wms_OLD,代码行数:103,代码来源:get_legend_graphic.py

示例12: StylistTkinter

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
class StylistTkinter(ttk.Frame):
    _WINDOW_TITLE = "Generic Title"
    opts = {}
    mplparams = {}

    """
    Present tool sytlization choices for a matplotlib plot.
    1. Create the plot required to build this up
    2. Create all of the appropriate widgets
    """

    def styleChange(self, name1, name2, op):
        """
        :param name1: http://www.tcl.tk/man/tcl8.4/TclCmd/trace.htm#M14
        :param name2: http://www.tcl.tk/man/tcl8.4/TclCmd/trace.htm#M14
        :param op: http://www.tcl.tk/man/tcl8.4/TclCmd/trace.htm#M14
        """
        logging.debug("styleChange detected with arguments (%s, %s, %s)" % (name1, name2, op))
        logging.debug("styleChange executing a change from to %s", self.mpl_global_style.get())
        plt.style.use(
            self.mpl_global_style.get()
        )  # TODO can you set this up to use name1 ? Yes, tk.StringVar() contains _name

        # clean up the existing stuff, deleting all of the components within the canvas
        self.canvas.get_tk_widget().delete("all")
        for child in self.mplframe.winfo_children():
            child.destroy()
        self.figure.clear()
        self.axes.clear()
        del self.line, self.axes, self.figure

        # recretae the plot, the frame it resides in is already created and useful
        self.createPlot()
        logging.debug("styleChange completed with new style changed to %s" % self.mpl_global_style.get())

    def loadOptions(self):
        logging.debug("loadOptions invocation")
        self.opts["mpl_style_idx"] = 0
        self.mplparams["styles"] = plt.style.available
        logging.debug('loadOptions set self.mplparams["styles"] = %s' % repr(self.mplparams["styles"]))
        optpath = os.path.join(os.getcwd(), "res", "stylist.opt")
        logging.debug("loading options: loading option file from %s" % (optpath))
        self.master.option_readfile(optpath)
        # fixme having some trouble with the namespaces of the options database

    def applyOptions(self):
        logging.debug("applyOptions invocation")
        plt.style.use(self.mplparams["styles"][self.opts["mpl_style_idx"]])
        for s in self.mplparams["styles"]:
            if self.opts["mpl_style_idx"] == s:
                self.mplparams["style_default"] = self.mplparams["styles"].index[s]

    def createPlot(self):
        logging.debug("createPlot invocation")
        self.figure = Figure(figsize=(5, 4), dpi=100)
        self.axes = self.figure.add_subplot(111)
        self.line, = self.axes.plot(self.x, self.y)
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.mplframe)
        self.canvas.show()
        # add the mpl toolbar to the toolbar
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.mplframe)
        self.toolbar.update()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def scaleFigAlpha(self, value):
        logging.debug("scaleFigAlpha called with alpha = %s" % value)
        self.figure.set_alpha(value)

    def createWidgets(self):
        logging.debug("createWidgets invocation")
        # todo add a menu region
        # a tk.DrawingArea containing the appropriate toolbars
        logging.debug("createWidgets building Matplotlib components for Tkinter integration")
        self.mplframe = ttk.Frame(class_="matplotstylist", name="mplframe")
        self.createPlot()
        self.mplframe.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        # The following contains the right hand style configuration area
        self.styleframe = ttk.Frame(class_="matplotstylist", name="styleframe")
        self.styleframe.pack(side=tk.RIGHT, anchor=tk.NE, fill=tk.X, expand=1, ipadx=2, ipady=2, padx=2, pady=2)
        # todo evaluation if you should Add a listbox describing the potentially available styles, permits compositing
        # self.lbx_styles = tk.Listbox(self, activestyle='dotbox',
        #                              listvariable=tk.StringVar(value=" ".join(self.mplparams["styles"])
        #                                                        , name="mplparams.styles"),
        #                              selectmode=tk.SINGLE)
        # self.lbx_styles.activate(self.opts['mpl_style_idx'])
        # self.lbx_styles.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        # Add an OptionsMenu describing the potentially available styles
        self.mpl_global_style = tk.StringVar()
        self.mpl_global_style.set(self.mplparams["styles"][self.opts["mpl_style_idx"]])
        self.omu_styles = tk.OptionMenu(self.styleframe, self.mpl_global_style, *self.mplparams["styles"])
        self.omu_styles.pack(side=tk.TOP, fill=tk.X, expand=1)

        logging.debug("createWidgets creating and populating styleframe artist's notebook")
        self.artist_notebook = ArtistStyleBook(self.styleframe)

        # add one tab for each type of artist in the plot
        """ populate the artists notebook with the controls to set/get each and every setable property
        of the artists used by the figure and its children.  Each artist may be inspected interactively
#.........这里部分代码省略.........
开发者ID:GaryHendrick,项目名称:MatplotStylist,代码行数:103,代码来源:stylist.py

示例13: quiver_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def quiver_response(lon,
                    lat,
                    dx,
                    dy,
                    request,
                    unit_vectors=False,
                    dpi=80):
    
    from django.http import HttpResponse

    xmin, ymin, xmax, ymax = wms_handler.get_bbox(request)
    width, height = wms_handler.get_width_height(request)
    
    colormap = wms_handler.get_colormap(request)

    climits = wms_handler.get_climits(request)

    cmax = 1.
    cmin = 0.
    
    if len(climits) == 2:
        cmin, cmax = climits
    else:
        logger.debug("No climits, default cmax to 1.0")

    # cmax = 10.

    #proj = get_pyproj(request)
    #x, y = proj(lon, lat)
    CRS = get_pyproj(request)
    x, y = pyproj.transform(EPSG4326, CRS, lon, lat) #TODO order for non-inverse?
    #logger.info("x, y: {0} {1}".format(x, y))
    
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    
    
    
    #scale to cmin - cmax
    # dx = cmin + dx*(cmax-cmin)
    # dy = cmin + dy*(cmax-cmin)
    mags = np.sqrt(dx**2 + dy**2)
    # mags[mags>cmax] = cmax
    mags[mags>cmax] = cmax
    mags[mags<cmin] = cmin

    import matplotlib as mpl
    cmap = mpl.cm.get_cmap(colormap)
    bounds = np.linspace(cmin, cmax, 15)
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

    #plot unit vectors
    if unit_vectors:
        ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=colormap)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm)
        #ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=colormap,norm=norm)

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:brianmckenna,项目名称:sci-wms_OLD,代码行数:75,代码来源:matplotlib_handler.py

示例14: tricontourf_response

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
def tricontourf_response(triang_subset,
                         data,
                         request,
                         dpi=80.0,
                         nlvls = 15):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """
    from django.http import HttpResponse

    xmin, ymin, xmax, ymax = wms_handler.get_bbox(request)
    width, height = wms_handler.get_width_height(request)
    
    colormap = wms_handler.get_colormap(request)
    
    cmin, cmax = wms_handler.get_climits(request)
    #logger.info('cmin/cmax: {0} {1}'.format(cmin, cmax))

    # TODO: check this?
    try:
        data[data>cmax] = cmax
        data[data<cmin] = cmin
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        logger.warning("tricontourf_response error: " + repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
    
    clvls = wms_handler.get_clvls(request)

    #proj = get_pyproj(request)
    #triang_subset.x, triang_subset.y = proj(triang_subset.x, triang_subset.y)
    CRS = get_pyproj(request)
    triang_subset.x, triang_subset.y = pyproj.transform(EPSG4326, CRS, triang_subset.x, triang_subset.y) #TODO order for non-inverse?
    #logger.info('TRANSFORMED triang_subset.x: {0}'.format(triang_subset.x))
    #logger.info('TRANSFORMED triang_subset.y: {0}'.format(triang_subset.y))

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    lvls = np.linspace(float(cmin), float(cmax), int(clvls))
    #logger.info('trang.shape: {0}'.format(triang_subset.x.shape))
    #logger.info('data.shape: {0}'.format(data.shape))
    ax.tricontourf(triang_subset, data, levels = lvls, cmap=colormap)

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)

    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    #plt.axis('off')

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:brianmckenna,项目名称:sci-wms_OLD,代码行数:65,代码来源:matplotlib_handler.py

示例15: ResidualPlot

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import set_alpha [as 别名]
class ResidualPlot(FigureCanvas):

    __instance = None

    def __init__(self):
        Global.event.task_selected.connect(self._on_task_selected)
        Global.event.plot_x_limit_changed.connect(self._on_x_limit_changed)
        Global.event.task_deleted.connect(self._on_task_deleted)
        Global.event.tasks_list_updated.connect(self._on_tasks_list_updated)

        self.task = None
        self.axes = None
        self.last_x_limit = []
        self.chi2s = []
        bg_color = str(QPalette().color(QPalette.Active, QPalette.Window).name())
        rcParams.update({'font.size': 10})

        self.figure = Figure(facecolor=bg_color, edgecolor=bg_color)
        self.figure.hold(False)
        super(ResidualPlot, self).__init__(self.figure)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.updateGeometry()
        self.hide()

    def _on_task_selected(self, task):
        self.set_task(task)
        self.redraw()

    def _on_task_deleted(self, task):
        if self.task == task:
            self.set_task(None)
            self.clear()

    def _on_tasks_list_updated(self):
        if not len(Global.tasks()):
            self.set_task(None)
            self.clear()

    def set_task(self, task):
        self.task = task

    def clear(self):
        self.figure.clf()
        self.figure.clear()
        self.draw()
        self.parent().chi2_label.hide()
        self.parent().chi2_value.hide()
        self.hide()
        gc.collect()

    def redraw(self):
        self.clear()

        if self.task.result.chi2 is None:
            self.parent().chi2_label.hide()
            self.parent().chi2_value.hide()
            self.hide()
            return

        self.chi2s.append(self.task.result.chi2)

        self.show()
        self.parent().chi2_label.show()
        self.parent().chi2_value.show()

        self.axes = self.figure.add_subplot(1, 1, 1)
        self.axes.grid(False)
        self.figure.set_alpha(0)
        self.axes.set_xlabel('Phase')
        self.axes.set_ylabel('Residual')

        phases = []
        delta_values = []

        keys = sorted(self.task.result.data().keys())

        for key in keys:
            if self.task.result.data()[key]['delta_value'] is not None:
                phases.append(key)
                delta_values.append(self.task.result.data()[key]['delta_value'])


        y_max = max(abs(min(delta_values)), abs(max(delta_values)))
        y_pad = (y_max / 100) * 10

        self.axes.set_autoscaley_on(False)
        self.axes.set_ylim([-(y_max + y_pad), y_max + y_pad])

        self.axes.set_autoscalex_on(False)
        self.axes.set_xlim(self.last_x_limit)

        color = QColor(0,0,0)
        min_chi2 = min(self.chi2s)
        if len(self.chi2s) == 1 :
            color = QColor(0,0,0)
        elif self.task.result.chi2 <= min_chi2 :
            color = QColor(0,139,0)
        else:
            color = QColor(255,0,0)
#.........这里部分代码省略.........
开发者ID:avladev,项目名称:transit-gui,代码行数:103,代码来源:Layout.py


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