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


Python PatchCollection.set_facecolor方法代码示例

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


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

示例1: draw_zips_3

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
def draw_zips_3(zctashapes, dfl, colorcol='', gamma=1.0):

    if len(colorcol)>0:
        c = dfl[colorcol].copy()#**gamma

    shapes = zctashapes
    Nshp    = len(shapes)

    cm    = plt.get_cmap('Dark2')
    cccol = cm(1.*c/max(c))

    #   -- plot --
    fig     = plt.figure()
    ax      = fig.add_subplot(111)
    for nshp in xrange(Nshp):
        ptchs   = []
        pts     = np.array(shapes[nshp].points)
        prt     = shapes[nshp].parts
        par     = list(prt) + [pts.shape[0]]

        for pij in xrange(len(prt)):
            ptchs.append(Polygon(pts[par[pij]:par[pij+1]]))

#        ax.add_collection(PatchCollection(ptchs,facecolor=cccol[nshp,:],edgecolor='k', linewidths=.1))
        pc = PatchCollection(ptchs,facecolor=cccol[nshp],norm=colors.PowerNorm(gamma=gamma),edgecolor='k', linewidths=.1)
        # for collection in pc:?
        pc.set_facecolor(cccol[nshp])

        ax.add_collection(pc)
    ax.set_xlim(-91,-82)
    ax.set_ylim(41,48)

    return ax
开发者ID:Feynman27,项目名称:datasciencetools,代码行数:35,代码来源:geotools.py

示例2: show_uboxes

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

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

	if not fig:
		fig = plt.figure()

	ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	plt.draw()
        plt.show()

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

示例3: show_uboxes_corners

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
def show_uboxes_corners( corners, width, S=None, col='b', ecol='k' ):
	"""
	This version takes the corners and width arrays as arguments
	instead.
	"""
	if corners.ndim != 2:
		raise Exception("show_uboxes_corners: dimension must be 2")
	if S is None:
		S = range( len(corners) )

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

	fig = plt.figure()
	ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	plt.show()
	
	return fig
开发者ID:caosuomo,项目名称:rads,代码行数:28,代码来源:gfx.py

示例4: BostonDensity

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
class BostonDensity(BostonScatter):
  def __init__(self, dataPoints):
    super(BostonDensity, self).__init__(dataPoints)
    return

  def dataDF(self):
    super(BostonDensity, self).dataDF()

    self.df_map['count'] = self.df_map['poly'].map(lambda x: int(len(filter(prep(x).contains, self.dataPoints))))
    self.df_map['POP100'] = self.df_map['POP100'].apply(float)
    self.df_map['density'] = (self.df_map['count'] * 1000) / self.df_map['POP100']
    # it's easier to work with NaN values when classifying
    self.df_map.replace(to_replace={'density': {0: np.nan}}, inplace=True)

    self.breaks = nb(
      self.df_map[self.df_map['density'].notnull()].density.values,
      initial=300,
      k=5)
    # the notnull method lets us match indices when joining
    jb = pd.DataFrame({'jenks_bins': self.breaks.yb}, index=self.df_map[self.df_map['density'].notnull()].index)
    self.df_map = self.df_map.join(jb)
    self.df_map.jenks_bins.fillna(-1, inplace=True)

    return

  def tracts(self):
    self.pc = PatchCollection(self.df_map['patches'], match_original=True)
    # impose our colour map onto the patch collection
    norm = mplc.Normalize()
    self.pc.set_facecolor(self.cmap(norm(self.df_map['jenks_bins'].values)))
    self.ax.add_collection(self.pc)
    return

  def colorScale(self):
    # Add a colour bar
    cb = colorbar_index(ncolors=len(self.jenks_labels), cmap=self.cmap, shrink=0.5, labels=self.jenks_labels)
    cb.ax.tick_params(labelsize=6)
    return

  def patchesDF(self):
    # use a blue colour ramp - we'll be converting it to a map using cmap()
    self.cmap = plt.get_cmap('Blues')
    # draw tracts with black outline. make suffolk (boston) thicker
    super(BostonDensity, self).patchesDF()

    self.jenks_labels = ["<= %0.1f per 1000 people (%s tracts)" % (b, c) for b, c in zip(
    self.breaks.bins, self.breaks.counts)]
    self.jenks_labels.insert(0, '<= 0.0 per 1000 people (%s tracts)' % len(self.df_map[self.df_map['density'].isnull()]))
    return

  def data(self):
    highest = '\n'.join([row['CT_ID_10'] + "," + 
                        str(row['density']) for i, row in self.df_map[
                        (self.df_map['jenks_bins'] == 4)][:30].sort(columns='density',
                        ascending=False).iterrows()])
    self.highest = 'TRACT_ID,DENSITY\n' + highest
    return
开发者ID:ElizabethBrooks,项目名称:HarvardREU2015_BARI,代码行数:59,代码来源:bostonmap.py

示例5: GreaterBostonDensity

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
class GreaterBostonDensity(GreaterBostonScatter):
  def __init__(self, dataPoints):
    super(GreaterBostonDensity, self).__init__(dataPoints)
    self.routeColor = 'r'
    return

  def dataDF(self):
    super(GreaterBostonDensity, self).dataDF()

    self.df_map['count'] = self.df_map['poly'].map(lambda x: int(len(filter(prep(x).contains, self.dataPoints))))
    self.df_map['density_m'] = self.df_map['count'] / self.df_map['area_m']
    self.df_map['density_km'] = self.df_map['count'] / self.df_map['area_km']
    # it's easier to work with NaN values when classifying
    self.df_map.replace(to_replace={'density_m': {0: np.nan}, 'density_km': {0: np.nan}}, inplace=True)

    self.breaks = nb(
      self.df_map[self.df_map['density_km'].notnull()].density_km.values,
      initial=300,
      k=5)
    # the notnull method lets us match indices when joining
    jb = pd.DataFrame({'jenks_bins': self.breaks.yb}, index=self.df_map[self.df_map['density_km'].notnull()].index)
    self.df_map = self.df_map.join(jb)
    self.df_map.jenks_bins.fillna(-1, inplace=True)

    return

  def patchesDF(self):
    # use a blue colour ramp - we'll be converting it to a map using cmap()
    self.cmap = plt.get_cmap('Blues')
    # draw tracts with black outline. make suffolk (boston) thicker
    self.df_map['patches'] = [PolygonPatch(row['poly'], ec='k',
      lw=0.25 if (row['COUNTY'] != suffolkID) else 0.8,
      alpha=.9, zorder=4) for i,row in self.df_map.iterrows()]

    self.jenks_labels = ["<=$%0.1f/km$^2$ (%s tracts)" % (b, c) for b, c in zip(
    self.breaks.bins, self.breaks.counts)]
    self.jenks_labels.insert(0, '<=$0.0/km$^2$ (%s tracts)' % len(self.df_map[self.df_map['density_km'].isnull()]))
    return

  def data(self):
    highest = '\n'.join([row['TRACT'] + "," + 
                        str(row['density_km']) for i, row in self.df_map[
                        (self.df_map['jenks_bins'] == 4)][:30].sort(columns='density_km',
                        ascending=False).iterrows()])
    self.highest = 'TRACT_ID,DENSITY\n' + highest
    return # function returns nothing

  def tracts(self):
    self.pc = PatchCollection(self.df_map['patches'], match_original=True)
    # impose our colour map onto the patch collection
    norm = mplc.Normalize()
    self.pc.set_facecolor(self.cmap(norm(self.df_map['jenks_bins'].values)))
    self.ax.add_collection(self.pc)
    return
开发者ID:ElizabethBrooks,项目名称:HarvardREU2015_BARI,代码行数:56,代码来源:bostonmap.py

示例6: gen_heat_map

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
def gen_heat_map(m, pickups):
    df_map = pd.DataFrame({
        'poly': [Polygon(xy) for xy in m.nyc],
        'zone_id': [zone['LocationID'] for zone in m.nyc_info]})
    df_map['area_km'] = df_map['poly'].map(lambda x: x.area) / 1000000
    area_map = df_map.groupby(['zone_id'])['area_km'].sum()
    count = 0
    fig = plt.figure()
    cmap = plt.get_cmap('Greys_r')
    color_map = np.zeros(len(df_map['poly']))
    pickup_map = {}
    plt.clf()
    norm = Normalize()

    # dateIndex, go over all the predicted lines
    for dateIndex in xrange(len(pickups)):
        pickups_count = pickups[dateIndex][2:]

        for i in xrange(len(pickups_count) - 2):
            index = i + 1
            if index in LOCATIONID_MAP.keys():
                pickup_map[LOCATIONID_MAP[index]] += pickups_count[i]
            else:
                pickup_map[index] = pickups_count[i]

        for i in xrange(len(m.nyc_info)):
            index = m.nyc_info[i]['LocationID']
            if index in LOCATIONID_MAP.keys():
                color_map[i] = pickup_map[LOCATIONID_MAP[index]]
            else:
                color_map[i] = pickup_map[index]

        ax = fig.add_subplot(111, frame_on=False, xticks=[], yticks=[])
        ax.set_title("Prediction")
        df_map['patches'] = [PolygonPatch(x, fc='white', ec='grey', lw=.25, alpha=1.0,
                                          zorder=4) for x in df_map['poly']]
        pc = PatchCollection(df_map['patches'].values, match_original=True)
        pc.set_facecolor(cmap(norm(color_map)))
        ax.add_collection(pc)
        min_x, min_y = m(lower_left[0], lower_left[1])
        max_x, max_y = m(upper_right[0], upper_right[1])

        ax.set_xlim(min_x, max_x)
        ax.set_ylim(min_y, max_y)
        ax.set_aspect(1)
        plt.tight_layout()
        fig.set_size_inches(16.76, 16.88)
        plt.show()

        #plt.savefig('data2/heat_map/nyc-' + str(date) + '-' + str(time) + '.png', dpi=100, alpha=True)
        count += 1
        if count % 100 == 0:
            print count
开发者ID:Jerryzcn,项目名称:rnn_hack,代码行数:55,代码来源:gen_zone_heat_map.py

示例7: _plot_ward_budget_with_color

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
    def _plot_ward_budget_with_color(self, to_map, axes):
        """Plot the budget per city ward, coloring each polygon according to
        "the ward's budget.

        to_map: the Basemap with the map of Toronto

        axes: the axes
        """

        # Plot the City Wards in Toronto. The borders of these polygons are
        # plot as they are in the Shapefile

        dummy = to_map.readshapefile(shapefile='./shp_dir/icitw_wgs84',
                                     name='city_wards',
                                     drawbounds=False, color='green')

        # The set of polygons (city-wards in Toronto) to add (to plot)
        patches = []
        # The ten-years budget per city-ward (in same order as its
        # geographical polygon
        ten_yrs_bdg = []

        for shape, shp_info in zip(to_map.city_wards, to_map.city_wards_info):
            # print shp_info
            # The GIS shapefile 'city_wards' ('icitw_wgs84') has the ward
            # number as the field with key 'SCODE_NAME' in that shapefile
            # (you need to .lstrip('0') from it, because, e.g., wards whose
            # number has a single digit are padded with left '0's in the
            # shapefile, but are nevertheless in the decimal system -just
            # padded with '0's, that's it- but Python will understand it
            # as in octal, not decimal syste.)

            shape_ward_number = int(shp_info['SCODE_NAME'].lstrip('0'))

            # the shapefile doesn't have the budget for this ward-number,
            # but the Excel spreadsheet we had done the ETL on it did

            ward_budget = self._total_budget_per_ward[shape_ward_number]
            # print "Ward: %02d, 10-years budget: %f, Ward-name: %s" % \
            #      (shape_ward_number, ward_budget, shp_info['NAME'])

            # append this budget and its associated geographical polygon
            ten_yrs_bdg.append(ward_budget)
            patches.append(Polygon(np.array(shape), True))

        cmap = plt.get_cmap('Greens')
        patch_collection = PatchCollection(patches, match_original=True)
        norm = Normalize(vmin=min(ten_yrs_bdg),
                         vmax=max(ten_yrs_bdg))
        patch_collection.set_facecolor(cmap(norm(ten_yrs_bdg)))

        axes.add_collection(patch_collection)
开发者ID:je-nunez,项目名称:Visualizing_investment_neighborhoods_Toronto,代码行数:54,代码来源:plot_excel_budget_toronto_neighborhoods.py

示例8: Createheatmap

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
def Createheatmap(m, breaks, MapData, jenksLabels, Coordinates, ComplaintChoice, FirstDate, LastDate):
    """ Create the heatmap charts. This module saves the chart as a png file. """

    CHFig = plt.figure()
    
    # use a blue color ramp - we'll be converting it to a map using cmap()
    cmap = plt.get_cmap('Blues')
    
    # draw NYC neighborhoods with grey (given by the hex number #555555) outlines.
    MapData['patches'] = MapData['poly'].map(lambda polys: PolygonPatch(polys, ec='#555555', lw=.2, alpha=1., zorder=4))
    
    
    PC = PatchCollection(MapData['patches'], match_original=True)  
    # impose our color map onto the patch collection.
    norm = Normalize()
    PC.set_facecolor(cmap(norm(MapData['jenks_bins'].values)))
    
    Axis = CHFig.add_subplot(111, axisbg='w', frame_on=False)
    Axis.add_collection(PC)

    # Provide some facts about classification method and where the data came from. 
    Axis.text(
        1.03, 0,
        'Classification method: natural breaks\n Contains 311 Complaint data. $\copyright$ 311 data from: https://nycopendata.socrata.com/',
        ha='right', va='bottom',
        size=5,
        color='#555555',
        transform=Axis.transAxes)
    
    # Add a color bar
    ColorBar = ColorBarIndex(ncolors=len(jenksLabels), cmap=cmap, shrink=0.5, labels=jenksLabels)
    ColorBar.ax.tick_params(labelsize=6)
    
    # Add a title
    plt.title("Densities of Complaint type: {0} \n  Date Range: {1} to {2}".format(ComplaintChoice, FirstDate, LastDate))
 
    # Draw a map scale.
    m.drawmapscale(
        Coordinates[0] + 0.08, Coordinates[1] + 0.015,
        Coordinates[0], Coordinates[1],
        10.,
        barstyle='fancy', labelstyle='simple',
        fillcolor1='w', fillcolor2='#555555',
        # #555555 refers to the gray color. 
        fontcolor='#555555',
        zorder=5)
    
    CHFig.set_size_inches(7.22, 5.25)
    title = 'Output/Heatmap_' + str(ComplaintChoice)+ "_" + str(pd.to_datetime(FirstDate).date()) + "_" + str(pd.to_datetime(LastDate).date())  + '.png'
    plt.savefig(title, dpi=100, alpha=True)
    plt.close()
开发者ID:abiesenb,项目名称:final_project,代码行数:53,代码来源:CreateHeatmap.py

示例9: IndicatorHeatMap

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
def IndicatorHeatMap(YEAR, LOCATION="Maryland", INDICATOR="None"):
    # Using a CSV of economic indicators, create a heatmap that
    # shows the data. This will be used under scatter and hexbin maps
    # if an indicator is selected.
    # This can probably be turned into an if/elif/else statement that
    # sets a common variable to a string based on the indicator chosen
    # and passes that variable through the breaks and jenks process.
    df_map = pd.merge(df_map, indicator_list, on="county_name", how="left")
    if INDICATOR == "None":
        pass
    elif INDICATOR == "Median Household Income":
        # Select county or neighborhood MHHI data from the passed year
        breaks = nb(
            df_map[df_map["mhhi"].notnull()].mhhi.values,
            initial=300,
            k=5)
            
        jb = pd.DataFrame({"jenks_bins":breaks.yb}, index=df_map[df_map["mhhi"].notnull()].index)
        df_map = df_map.join(jb)
        df_map.jenks_bins.fillna(-1, inplace=True)

        jenks_labels = ["Median Household Income:\n<= %f" % b for b in breaks.bins]
    elif INDICATOR == "Millennial Population Growth":
        # Select county or neighborhood Millennial population data from the passed year
        pass
    else:
        print "The %s indicator is not yet available in this program." % INDICATOR
    
    ax = fig.add_subplot(111, axisbg = "w", frame_on = False)

    # Change get_cmap color based on INDICATOR    
    cmap = plt.get_cmap("Blues")
    df_map["patches"] = df_map["poly"].map(lambda x: PolygonPatch(x, ec="#555555", lw=.2, alpha=1, zorder=4))
    pc = PatchCollection(df_map["patches"], match_original=True)
    norm = Normalize()
    pc.set_facecolor(cmap(norm(df_map["jenks_bins"].values)))
    ax.add_collection(pc)

    cb = colorbar_index(ncolors=len(jenks_labels), cmap=cmap, shrink=0.5, labels=jenks_labels)
    cb.ax.tick_params(labelsize=8)

    m.drawmapscale(
        -125, 20,
        -125, 20,
        10.,
        barstyle = "fancy", labelstyle = "simple",
        fillcolor1 = "w", fillcolor2 = "w",
        fontcolor = "w",
        zorder=9,
        units = "m",
        fontsize =7)    
开发者ID:pjdougherty,项目名称:Geospatial,代码行数:53,代码来源:Map.py

示例10: _get_fpt_ell_collection

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [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

示例11: plot_map

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
def plot_map(m, coords, df_map, info, savefig=False):
    plt.clf()
    fig = plt.figure()
    ax = fig.add_subplot(111, axisbg='w', frame_on=True)
    # draw wards with grey outlines
    norm = Normalize()
    for i in xrange(5):
        color = colormaps[i]
        cmap = plt.get_cmap(color)
        cond = (df_map['class'] == (i+1))
        inx = df_map[cond].index
        if cond.sum() > 0:
            pc = PatchCollection(df_map[cond]['patches'],
                                 match_original=True, alpha=0.75)
            pc.set_facecolor(cmap(norm(df_map.loc[inx, 'cls_%d'%(i+1)].values)))
            ax.add_collection(pc)
    if (df_map['class'] == 0).sum() > 0:
        pc = PatchCollection(df_map[df_map['class'] == 0]['patches'],
                             match_original=True, alpha=0.1
                             )
        pc.set_facecolor('grey')
        ax.add_collection(pc)
    x, y = m(coords[0], coords[3]+0.006)

    details = ax.annotate(info, xy=(x, y), size=20, color='k')

    # Draw a map scale
    m.drawmapscale(
        coords[0]+0.02, coords[1]-0.004,
        coords[0], coords[1],
        2,
        barstyle='fancy', labelstyle='simple',
        fillcolor1='w', fillcolor2='#555555',
        fontcolor='#555555', units='mi',
        zorder=5)

    legend_patches = []
    for i in range(5):
        legend_patches.append(mpatches.Patch(color='C%d' % i,
                                             label=classes[i]))
    ax.legend(handles=legend_patches, loc='upper right')

    fig.set_size_inches(12, 12)
    plt.tight_layout()
    if savefig:
        plt.savefig(savefig, dpi=200, alpha=True)
开发者ID:livenb,项目名称:crime_prediction,代码行数:48,代码来源:sf_map.py

示例12: plot_trajectory_ellipse

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [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

示例13: ZoomPerspectiveEtopo

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
def ZoomPerspectiveEtopo():
    
    fig, ax = plt.subplots(figsize=(3, 2.5))

    # setup Lambert Conformal basemap.
    print("I am trying to get rid of these bloody lakes")
    m = Basemap(width=1800000,height=1500000,projection='lcc',area_thresh=10000000.,
                resolution='h',lat_1=45.,lat_2=55,lat_0=25.7,lon_0=91.5)
    # draw coastlines.
    #m.drawrivers()
    m.drawcoastlines()
    # draw a boundary around the map, fill the background.
    # this background will end up being the ocean color, since
    # the continents will be drawn on top.
    m.drawmapboundary(fill_color='aqua')
    # fill continents, set lake color same as ocean color.
    m.fillcontinents(color='peru',lake_color='white')
    # draw parallels and meridians.
    # label parallels on right and top
    # meridians on bottom and left
    parallels = np.arange(0.,81,5.)
    # labels = [left,right,top,bottom]
    m.drawparallels(parallels,labels=[False,True,True,False])
    meridians = np.arange(10.,351.,5.)
    m.drawmeridians(meridians,labels=[True,False,False,True])
    m.drawcountries()
    m.readshapefile('Mega_divide_footprint', 'MDF')

    # All this stuff from:
    # http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/
    df_poly = pd.DataFrame({
            'shapes': [Polygon(np.array(shape), True) for shape in m.MDF]})

    print(df_poly)

    #df_poly = df_poly.merge(new_areas, on='area', how='left')
    cmap = plt.get_cmap('Oranges')   
    pc = PatchCollection(df_poly.shapes, zorder=2, alpha = 0.5)
    pc.set_facecolor("gray")
    ax.add_collection(pc)  

    FigFileName = "Test.svg"
    FigFormat = "svg"

    plt.savefig(FigFileName,format=FigFormat,dpi=200)       
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:47,代码来源:Basemap_test.py

示例14: plot_map

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [as 别名]
 def plot_map(self, title_name, cmap=None, figwidth=14,
              bins=[0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.],
              bin_labels=None, save_path=None):
     if cmap is None:
         cmap = self._set_colormap()
     self.df_map['bins'] = self.df_map[self.values_col].apply(self._get_bins, args=(bins,))
     if bin_labels is None:
         bin_labels = ["{0}%".format(100 * x) for x in bins]
     fig = plt.figure(figsize=(figwidth, figwidth * self.h / self.w))
     ax = fig.add_subplot(111, axisbg = 'w', frame_on = False)
     func = lambda x: PolygonPatch(x, ec='#111111', lw=.8, alpha=1.,
                                   zorder=4)
     self.df_map['patches'] = self.df_map['poly'].map(func)
     pc = PatchCollection(self.df_map['patches'], match_original=True)
     #cmap_rng = (self.df_map['bins'].values - min(bins)) / float(max(bins))
     #cmap_rng = (self.df_map['bins'].values - self.df_map['bins'].values.min())/ \
     #           (self.df_map['bins'].values.max() - float(self.df_map['bins'].values.min()))
     #cmap_list = [cmap(val) for val in cmap_rng]
     cmap_list = [cmap(val) for val in self.df_map[self.values_col].values]
     pc.set_facecolor(cmap_list)
     ax.add_collection(pc)
     self.map.drawmapscale(self.coords[0] + 0.08,
                           self.coords[1] + -0.01,
                           self.coords[0],
                           self.coords[1],
                           10.,
                           fontsize=16,
                           barstyle='fancy',
                           labelstyle='simple',
                           fillcolor1='w',
                           fillcolor2='#555555',
                           fontcolor='#555555',
                           zorder=5,
                           ax=ax)
     cbar = self._create_colorbar(cmap, ncolors=len(bin_labels) + 1,
                                  labels=bin_labels, shrink=0.5)
     cbar.ax.tick_params(labelsize=16)
     if title_name is not None:
         fig.suptitle(title_name, fontdict={'size':24, 'fontweight':'bold'},
                      y=0.92)
     if save_path is not None:
         plt.savefig(save_path, dpi=100, frameon=False, bbox_inches='tight', pad_inches=0.5)
开发者ID:hendrikTpl,项目名称:SEA_traffic_accident_prediction,代码行数:44,代码来源:seattle_choropleth.py

示例15: show_box

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_facecolor [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


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