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


Python PatchCollection.set_color方法代码示例

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


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

示例1: plot_trajectory_ellipse

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

示例2: range

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_color [as 别名]
# define a colorramp
num_colors = 12
cm = plt.get_cmap('Blues')
blues = [cm(1.*i/num_colors) for i in range(num_colors)]

# add colorbar legend
cmap = mpl.colors.ListedColormap(blues)
# define the bins
bounds = np.linspace(0.0, 1.0, num_colors)

# read each states shapefile
for key in state_codes.keys():
    m.readshapefile('../input/shapefiles/pums/tl_2013_{0}_puma10'.format(key),
                    name='state', drawbounds=True, default_encoding='latin-1')
                    
    # loop through each PUMA and assign a random color from our colorramp
    for info, shape in zip(m.state_info, m.state):
        patches = [Polygon(np.array(shape), True)]
        pc = PatchCollection(patches, edgecolor='k', linewidths=1., zorder=2)
        pc.set_color(random.choice(blues))
        ax.add_collection(pc)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, ticks=bounds, boundaries=bounds,
                               format='%1i')
cb.ax.set_yticklabels([str(round(i, 2)) for i in bounds])

plt.savefig('map.png')

开发者ID:cogfor,项目名称:Census-Data-Exploration,代码行数:31,代码来源:basemap.py

示例3: PlotConductors

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_color [as 别名]

#.........这里部分代码省略.........
        """
        Runs logic for finding which conductors can be plotted and run appropriate patch creation functions.
        Args:
            solver: Warp fieldsolver object containing conductors to be plotted.

        Returns:
                None
        """

        # Iterate through all conductor lists in the solver
        for key in solver.installedconductorlists:
            # Iterate through all conductor objects
            for conductor in solver.installedconductorlists[key]:
                # Perform check to make sure this is a conductor the code knows how to handle
                for obj_type in self.conductor_types:
                    if isinstance(conductor, getattr(field_solvers.generateconductors, obj_type)):
                        if conductor.permittivity is None:
                            self.conductors.append(self.set_rectangle_patch(conductor))
                            self.voltages.append(conductor.voltage)
                        if conductor.permittivity is not None:
                            self.dielectrics.append(self.set_rectangle_patch(conductor, dielectric=True))
                            self.permittivities.append(conductor.permittivity)

    def conductor_collection(self):
        # TODO: Once dielectrics register with solver add in loop to append them to dielectric array
        if not self.plot_axes:
            self.create_axes()

        if len(self.voltages) > 0:
            self.set_collection_colors(self.conductor_patch_colors, self.voltages, self.map)

            # Assign patches for conductors to the plot axes
            self.conductor_patches = PatchCollection(self.conductors)
            self.conductor_patches.set_color(self.conductor_patch_colors)
            self.plot_axes.add_collection(self.conductor_patches)

        if len(self.permittivities) > 0:
            self.set_collection_colors(self.dielectric_patch_colors, self.permittivities, plt.cm.viridis)

            # Assign patches for dielectrics to the plot axes
            self.dielectric_patches = PatchCollection(self.dielectrics)
            self.dielectric_patches.set_color(self.dielectric_patch_colors)
            self.dielectric_patches.set_hatch('//')
            self.plot_axes.add_collection(self.dielectric_patches)

            # Setup the legend and set data for legend axes
            self.create_legend()
        if len(self.voltages) > 0:
            cond_legend = self.legend_axes.legend(handles=self.conductor_legend_handles,
                                    bbox_to_anchor=self.legend_anchor,
                                    borderaxespad=0.,
                                    fontsize=self.legend_fontsize,
                                    title='Voltage (V)')
            self.legend_axes.add_artist(cond_legend)
        if len(self.permittivities) > 0:
            diel_legend = self.legend_axes.legend(handles=self.dielectric_legend_handles,
                                    bbox_to_anchor=(self.legend_anchor[0] + 0.05, self.legend_anchor[1] - 0.2),
                                    borderaxespad=0.,
                                    fontsize=self.legend_fontsize,
                                    title='   Relative\nPermittivity')
            self.legend_axes.add_artist(diel_legend)

    def set_collection_colors(self, color_collection, color_values, map):
        # Wanted color scaling to always be red for negative and blue for positive (assuming bl-r colormap)
        # Created custom linear scaling to using halves of color map for +/- consistently, even if only one sign present
开发者ID:radiasoft,项目名称:rswarp,代码行数:69,代码来源:ConductorPlot.py

示例4: range

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_color [as 别名]
num_colors = 12
cm = plt.get_cmap("coolwarm")
blues = [cm(1.0 * i / num_colors) for i in range(num_colors)]

# add colorbar legend
cmap = mpl.colors.ListedColormap(blues)

# read each states shapefile
for key in state_codes.keys()[0 : int(sys.argv[2])]:
    m.readshapefile(
        "../shapefiles/pums/tl_2013_{0}_puma10".format(key), name="state", drawbounds=True, default_encoding="latin-1"
    )
    # loop through each PUMA and assign a random color from our colorramp
    for info, shape in zip(m.state_info, m.state):
        idPuma = int(info.get("PUMACE10"))
        val = data[((data.PUMA == idPuma) & (data.ST == int(key)))]["value"]
        bounds = pd.Series(np.linspace(min(data.value), max(data.value), num_colors))
        bins = pd.Series(np.linspace(min(data.value), max(data.value), num_colors + 1))
        bucket = bounds[pd.Series(np.histogram(val, bins)[0]) == 1].index.values
        patches = [Polygon(np.array(shape), True)]
        pc = PatchCollection(patches, edgecolor="k", linewidths=1.0, zorder=2)
        pc.set_color(blues[bucket])
        ax.add_collection(pc)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, ticks=bounds, boundaries=bounds, format="%1i")
cb.ax.set_yticklabels([str(round(i, 2)) for i in bounds])

plt.savefig("%s.png" % sys.argv[3])
开发者ID:bguOIQ,项目名称:everthoughtabout,代码行数:32,代码来源:Census+PUMA+plotting.py

示例5: range

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_color [as 别名]
cm=plt.get_cmap('hot')
reds=[cm(1.0*i/num) for i in range(num-1,-1,-1)]
cmap = mpl.colors.ListedColormap(reds)

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111, axisbg='w', frame_on=False)
fig.suptitle('Percentage of children without Internet access', fontsize=20)

m = Basemap(width=5000000,height=3500000,resolution='l',projection='aea',lat_1=30.,lat_2=50,lon_0=-96,lat_0=38)

for key in state_codes.keys():
    m.readshapefile('/home/krishna/Documents/My_Docs/PBL/data/shapefiles/pums/tl_2013_{0}_puma10'.format(key), name='state', drawbounds=True)
    new_key = int(key)
    
    for info, shape in zip(m.state_info, m.state):
        id=int(info['PUMACE10'])
        value=noNet[(noNet['ST']==new_key) & (noNet['PUMA']==id)]['perc']
        color=int(value/10)
        patches = [Polygon(np.array(shape), True)]
        pc = PatchCollection(patches, edgecolor='k', linewidths=1., zorder=2)
        pc.set_color(reds[color])
        ax.add_collection(pc)

ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8])
bounds=np.linspace(0,10,num)
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, ticks=bounds, boundaries=bounds)
cb.ax.set_yticklabels([str(round(i)*10) for i in bounds])

plt.show()
plt.savefig("children_without_internet_access.png")
开发者ID:MSRIT-CSE,项目名称:PBL_15_IncomeDA,代码行数:32,代码来源:child_no_int_acc_.py

示例6: zip

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_color [as 别名]
    else:
        mNormal.readshapefile('shapefiles/pums/tl_2013_{0}_puma10'.format(key),name='state', drawbounds=True)
        m = mNormal

    # loop through each PUMA and assign the correct color to its shape
    for info, shape in zip(m.state_info, m.state):
        dataForStPuma = data[key][info['PUMACE10']]

        # get the percentage of households with Internet access
        woAccess = (dataForStPuma == 3)
        accessPerc = 1-(sum(woAccess)/(1.0*len(dataForStPuma)))
        colorInd = int(round(accessPerc*num_colors))

        patches = [Polygon(np.array(shape), True)]
        pc = PatchCollection(patches, edgecolor='k', linewidths=1., zorder=2)
        pc.set_color(colorGradient[colorInd])
        if (state_codes[key] == "Alaska"):
            axAlaska.add_collection(pc)
        elif (state_codes[key] == "Hawaii"):
            axHawaii.add_collection(pc)
        else:
            ax.add_collection(pc)


# add colorbar legend
cmap = mpl.colors.ListedColormap(colorGradient)
# define the bins and normalize
bounds = np.linspace(0,100,num_colors)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.82, 0.1, 0.03, 0.8])
开发者ID:openmachinesblog,项目名称:visualization-census-2013,代码行数:33,代码来源:basic.py

示例7: plot_polygon_collection

# 需要导入模块: from matplotlib.collections import PatchCollection [as 别名]
# 或者: from matplotlib.collections.PatchCollection import set_color [as 别名]
def plot_polygon_collection(ax, geoms, colors_or_values, plot_values,
                            vmin=None, vmax=None, cmap=None,
                            edgecolor='black', alpha=0.5, linewidth=1.0, **kwargs):
    """
    Plots a collection of Polygon and MultiPolygon geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed)

    colors_or_values : a sequence of `N` values or RGBA tuples
        It should have 1:1 correspondence with the geometries (not their components).

    plot_values : bool
        If True, `colors_or_values` is interpreted as a list of values, and will
        be mapped to colors using vmin/vmax/cmap (which become required).
        Otherwise `colors_or_values` is interpreted as a list of colors.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    from descartes.patch import PolygonPatch
    from matplotlib.collections import PatchCollection

    components, component_colors_or_values = _flatten_multi_geoms(
        geoms, colors_or_values)

    # PatchCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']
    collection = PatchCollection([PolygonPatch(poly) for poly in components],
                                 linewidth=linewidth, edgecolor=edgecolor,
                                 alpha=alpha, **kwargs)

    if plot_values:
        collection.set_array(np.array(component_colors_or_values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)
    else:
        # set_color magically sets the correct combination of facecolor and
        # edgecolor, based on collection type.
        collection.set_color(component_colors_or_values)

        # If the user set facecolor and/or edgecolor explicitly, the previous
        # call to set_color might have overridden it (remember, the 'color' may
        # have come from plot_series, not from the user). The user should be
        # able to override matplotlib's default behavior, by setting them again
        # after set_color.
        if 'facecolor' in kwargs:
            collection.set_facecolor(kwargs['facecolor'])
        if edgecolor:
            collection.set_edgecolor(edgecolor)

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
开发者ID:brendancol,项目名称:geopandas,代码行数:65,代码来源:plotting.py


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