本文整理汇总了Python中matplotlib.colors.ColorConverter类的典型用法代码示例。如果您正苦于以下问题:Python ColorConverter类的具体用法?Python ColorConverter怎么用?Python ColorConverter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ColorConverter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: parse_list_of_colors
def parse_list_of_colors(self, number, colors):
from matplotlib.colors import ColorConverter
cconvert = ColorConverter()
if number != len(colors):
raise ValueError("the length of colors must be the number of groups")
rgbcolors = [cconvert.to_rgb(c) for c in colors]
return rgbcolors
开发者ID:dimaslave,项目名称:pele,代码行数:7,代码来源:disconnectivity_graph.py
示例2: get_rgb_hexad_color_palete
def get_rgb_hexad_color_palete():
"""Returns a list of RGB values with the color palette used to plot the
transit vehicles returned by NextBus. Each entry returned in the color
palette has the RGB hexadecimal format, and without the prefix '0x' as
for colors in Google Maps, nor the prefix '#' for the matplotlib color.
Ie., the entry for blue is returned as '0000FF' and for red 'FF0000'."""
# We don't use these color names directly because their intensity might
# be (are) reflected diferently between between the remote server and
# matplotlib, and this difference in rendering a same color affects the
# color-legend in matplotlib. For this reason too, we don't need to use
# only the named colors in Google Maps but more in matplotlib, for in
# both cases hexadecimal RGB values are really used.
high_contrast_colors = ["green", "red", "blue", "yellow", "aqua",
"brown", "gray", "honeydew", "purple",
"turquoise", "magenta", "orange"]
from matplotlib.colors import ColorConverter, rgb2hex
color_converter = ColorConverter()
hex_color_palette = [rgb2hex(color_converter.to_rgb(cname))[1:] for \
cname in high_contrast_colors]
# matplotlib.colors.cnames[cname] could have been used instead of rgb2hex
return hex_color_palette
开发者ID:je-nunez,项目名称:NextBus_real_time_Route_Bus_locations_to_Pandas_Dataframe,代码行数:26,代码来源:plot_dataframe_nextbus_vehicle_locations.py
示例3: make_colormap
def make_colormap(self, key):
""" define a new color map based on values specified in the color_scale file for the key"""
#colors = {0.1:'#005a00', 0.2:'#6e0dc6',0.3:'#087fdb',0.4:'#1c47e8',0.5:'#007000'} # parsed result format from color_scale file
colors = self.colorTable[key]
z = sort(colors.keys()) ## keys
n = len(z)
z1 = min(z)
zn = max(z)
x0 = (z - z1) / (zn - z1) ## normalized keys
CC = ColorConverter()
R = []
G = []
B = []
for i in range(n):
## i'th color at level z[i]:
Ci = colors[z[i]]
if type(Ci) == str:
## a hex string of form '#ff0000' for example (for red)
RGB = CC.to_rgb(Ci)
else:
## assume it's an RGB triple already:
RGB = Ci
R.append(RGB[0])
G.append(RGB[1])
B.append(RGB[2])
cmap_dict = {}
cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))] ## normalized value in X0
cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))]
mymap = LinearSegmentedColormap(key,cmap_dict)
return mymap, z
开发者ID:jjhelmus,项目名称:lrose-soloPy,代码行数:32,代码来源:ColorMap.py
示例4: plot_em
def plot_em(step, X, K, amps, means, covs, z,
newamps, newmeans, newcovs, show=True):
import pylab as plt
from matplotlib.colors import ColorConverter
(N,D) = X.shape
if z is None:
z = np.zeros((N,K))
for k,(amp,mean,cov) in enumerate(zip(amps, means, covs)):
z[:,k] = amp * gaussian_probability(X, mean, cov)
z /= np.sum(z, axis=1)[:,np.newaxis]
plt.clf()
# snazzy color coding
cc = np.zeros((N,3))
CC = ColorConverter()
for k in range(K):
rgb = np.array(CC.to_rgb(colors[k]))
cc += z[:,k][:,np.newaxis] * rgb[np.newaxis,:]
plt.scatter(X[:,0], X[:,1], color=cc, s=9, alpha=0.5)
ax = plt.axis()
for k,(amp,mean,cov) in enumerate(zip(amps, means, covs)):
plot_ellipse(mean, cov, 'k-', lw=4)
plot_ellipse(mean, cov, 'k-', color=colors[k], lw=2)
plt.axis(ax)
if show:
plt.show()
开发者ID:LocalGroupAstrostatistics2015,项目名称:Unsupervised,代码行数:31,代码来源:utils.py
示例5: make_colormap
def make_colormap(colors):
z = np.sort(colors.keys())
n = len(z)
z1 = min(z)
zn = max(z)
x0 = (z - z1) / (zn - z1)
CC = ColorConverter()
R = []
G = []
B = []
for i in range(n):
Ci = colors[z[i]]
if type(Ci) == str:
RGB = CC.to_rgb(Ci)
else:
RGB = Ci
R.append(RGB[0])
G.append(RGB[1])
B.append(RGB[2])
cmap_dict = {}
cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))]
cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))]
mymap = LinearSegmentedColormap('mymap',cmap_dict)
return mymap
开发者ID:olga,项目名称:olga_model,代码行数:27,代码来源:colormaps.py
示例6: _set_ax_pathcollection_to_bw
def _set_ax_pathcollection_to_bw(collection, ax, style, colormap):
'''helper function for converting a pathcollection to black and white
Parameters
----------
collection : pathcollection
ax : axes
style : {GREYSCALE, HATCHING}
colormap : dict
mapping of color to B&W rendering
'''
color_converter = ColorConverter()
colors = {}
for key, value in color_converter.colors.items():
colors[value] = key
rgb_orig = collection._facecolors_original
rgb_orig = [color_converter.to_rgb(row) for row in rgb_orig]
new_color = [color_converter.to_rgba(colormap[entry]['fill']) for entry
in rgb_orig]
new_color = np.asarray(new_color)
collection.update({'facecolors' : new_color})
collection.update({'edgecolors' : new_color})
开发者ID:JamesPHoughton,项目名称:EMAworkbench,代码行数:26,代码来源:b_and_w_plotting.py
示例7: __init__
def __init__(self, c1, c2=None, cluster=None):
c= ColorConverter()
if c2 is None:
self.mincol,self.maxcol = c.to_rgba(c1[0]), c.to_rgba(c1[1])
else:
self.mincol, self.maxcol = c.to_rgba(c1), c.to_rgba(c2)
self.cluster = cluster
开发者ID:BenjaminPeter,项目名称:pooGUI,代码行数:7,代码来源:SampleFrame.py
示例8: _set_ax_polycollection_to_bw
def _set_ax_polycollection_to_bw(collection, ax, style):
'''helper function for converting a polycollection to black and white
Parameters
----------
collection : polycollection
ax : axes
style : {GREYSCALE, HATCHING}
'''
if style==GREYSCALE:
color_converter = ColorConverter()
for polycollection in ax.collections:
rgb_orig = polycollection._facecolors_original
if rgb_orig in COLORMAP.keys():
new_color = color_converter.to_rgba(COLORMAP[rgb_orig]['fill'])
new_color = np.asarray([new_color])
polycollection.update({'facecolors' : new_color})
polycollection.update({'edgecolors' : new_color})
elif style==HATCHING:
rgb_orig = collection._facecolors_original
collection.update({'facecolors' : 'none'})
collection.update({'edgecolors' : 'white'})
collection.update({'alpha':1})
for path in collection.get_paths():
p1 = mpl.patches.PathPatch(path, fc="none",
hatch=COLORMAP[rgb_orig]['hatch'])
ax.add_patch(p1)
p1.set_zorder(collection.get_zorder()-0.1)
开发者ID:feilos,项目名称:EMAworkbench,代码行数:32,代码来源:b_and_w_plotting.py
示例9: IsValidColour
def IsValidColour(self, color):
"""Checks if color is a valid matplotlib color"""
try:
cc = ColorConverter()
cc.to_rgb(color)
return True
except ValueError: #invalid color
return False
开发者ID:nrao,项目名称:deap,代码行数:8,代码来源:PlotEditFrame.py
示例10: MplToWxColour
def MplToWxColour(self, color):
"""Converts matplotlib color (0-1) to wx.Colour (0-255)"""
try:
cc = ColorConverter()
rgb = tuple([d*255 for d in cc.to_rgb(color)])
return wx.Colour(*rgb)
except ValueError: #invalid color
return wx.Colour()
开发者ID:nrao,项目名称:deap,代码行数:8,代码来源:PlotEditFrame.py
示例11: drawImpacts
def drawImpacts(self):
# Load the dataset
dataset = self.datasetManager.loadDataset(self.datasetManager.getAccuracyComplete())
# Create the scene
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
ax.set_xlabel('X (horizontal in mm)')
ax.set_ylabel('Y (vertical in mm)')
ax.set_zlabel('Z (depth in mm)')
colorConverter = ColorConverter()
for data in dataset:
result = self.featureExtractor.getFeatures(data)
# Processed data
fingerTipCoordinates = self.featureExtractor.fingerTip[0]
eyeCoordinates = self.featureExtractor.eyePosition[0]
targetCoordinates = data.target
depthMap = data.depth_map
fingerTipCoordinates.append(self.utils.getDepthFromMap(depthMap, fingerTipCoordinates))
eyeCoordinates.append(self.utils.getDepthFromMap(depthMap, eyeCoordinates))
closest = self.trigonometry.findIntersection(fingerTipCoordinates, eyeCoordinates, targetCoordinates, self.expectedRadius)
if closest != None:
x = closest[0]-targetCoordinates[0]
y = closest[1]-targetCoordinates[1]
z = closest[2]-targetCoordinates[2]
distance = self.trigonometry.findIntersectionDistance(fingerTipCoordinates, eyeCoordinates, targetCoordinates, self.expectedRadius)
red = 1-(distance/200)
if red < 0:
red = 0
elif red > 1:
red = 1
blue = 0+(distance/200)
if blue < 0:
blue = 0
elif blue > 1:
blue = 1
cc = colorConverter.to_rgba((red,0,blue), 0.4)
# Draw the impact point
ax.scatter(x, y, z, color=cc, marker="o", s=50)
# Draw the target point
ax.scatter(0, 0, 0, c="#000000", marker="o", color="#000000", s=100)
plt.show()
开发者ID:EdwardBetts,项目名称:pointing-gesture-recognition,代码行数:58,代码来源:accuracy.py
示例12: plotBoundary
def plotBoundary(dataset='iris', split=0.7, doboost=False, boostiter=5, covdiag=True, filename='', exportImg=False):
X, y, pcadim = fetchDataset(dataset)
xTr, yTr, xTe, yTe, trIdx, teIdx = trteSplitEven(X, y, split)
pca = decomposition.PCA(n_components=2)
pca.fit(xTr)
xTr = pca.transform(xTr)
xTe = pca.transform(xTe)
pX = np.vstack((xTr, xTe))
py = np.hstack((yTr, yTe))
if doboost:
## Boosting
# Compute params
priors, mus, sigmas, alphas = trainBoost(xTr, yTr, T=boostiter, covdiag=covdiag)
else:
## Simple
# Compute params
prior = computePrior(yTr)
mu, sigma = mlParams(xTr, yTr)
xRange = np.arange(np.min(pX[:, 0]), np.max(pX[:, 0]), np.abs(np.max(pX[:, 0]) - np.min(pX[:, 0])) / 100.0)
yRange = np.arange(np.min(pX[:, 1]), np.max(pX[:, 1]), np.abs(np.max(pX[:, 1]) - np.min(pX[:, 1])) / 100.0)
grid = np.zeros((yRange.size, xRange.size))
for (xi, xx) in enumerate(xRange):
for (yi, yy) in enumerate(yRange):
if doboost:
## Boosting
grid[yi, xi] = classifyBoost(np.matrix([[xx, yy]]), priors, mus, sigmas, alphas, covdiag=covdiag)
else:
## Simple
grid[yi, xi] = classify(np.matrix([[xx, yy]]), prior, mu, sigma, covdiag=covdiag)
classes = range(np.min(y), np.max(y) + 1)
ys = [i + xx + (i * xx) ** 2 for i in range(len(classes))]
colormap = cm.rainbow(np.linspace(0, 1, len(ys)))
plt.hold(True)
conv = ColorConverter()
for (color, c) in zip(colormap, classes):
try:
CS = plt.contour(xRange, yRange, (grid == c).astype(float), 15, linewidths=0.25,
colors=conv.to_rgba_array(color))
except ValueError:
pass
xc = pX[py == c, :]
plt.scatter(xc[:, 0], xc[:, 1], marker='o', c=color, s=40, alpha=0.5)
plt.xlim(np.min(pX[:, 0]), np.max(pX[:, 0]))
plt.ylim(np.min(pX[:, 1]), np.max(pX[:, 1]))
if exportImg:
plt.savefig(filename + '.png', dpi=400)
plt.clf()
else:
plt.show()
开发者ID:haidelber,项目名称:machinelearning15kth,代码行数:57,代码来源:lab3.py
示例13: genImage
def genImage(self):
"""Create a PNG from the contents of this flowable.
Required so we can put inline math in paragraphs.
Returns the file name.
The file is caller's responsability.
"""
dpi = 72
scale = 10
try:
import Image
import ImageFont
import ImageDraw
except ImportError:
from PIL import (
Image,
ImageFont,
ImageDraw,
)
if not HAS_MATPLOTLIB:
img = Image.new('RGBA', (120, 120), (255, 255, 255, 0))
else:
width, height, descent, glyphs, rects, used_characters = \
self.parser.parse(enclose(self.s), dpi,
prop=FontProperties(size=self.fontsize))
img = Image.new('RGBA', (int(width * scale), int(height * scale)),
(255, 255, 255, 0))
draw = ImageDraw.Draw(img)
for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
font = ImageFont.truetype(fontname, int(fontsize * scale))
tw, th = draw.textsize(chr(num), font=font)
# No, I don't understand why that 4 is there.
# As we used to say in the pure math
# department, that was a numerical solution.
col_conv = ColorConverter()
fc = col_conv.to_rgb(self.color)
rgb_color = (
int(fc[0] * 255),
int(fc[1] * 255),
int(fc[2] * 255)
)
draw.text((ox * scale, (height - oy - fontsize + 4) * scale),
chr(num), font=font, fill=rgb_color)
for ox, oy, w, h in rects:
x1 = ox * scale
x2 = x1 + w * scale
y1 = (height - oy) * scale
y2 = y1 + h * scale
draw.rectangle([x1, y1, x2, y2], (0, 0, 0))
fh, fn = tempfile.mkstemp(suffix=".png")
os.close(fh)
img.save(fn)
return fn
开发者ID:aquavitae,项目名称:rst2pdf-py3-dev,代码行数:56,代码来源:math_flowable.py
示例14: validate_color
def validate_color(self, color):
""" Function for validating Matplotlib user input color choice
"""
print color
c = ColorConverter()
try:
print c.to_rgb(color)
except:
return False
return True
开发者ID:c11,项目名称:TSTools,代码行数:10,代码来源:SavePlotDialog.py
示例15: compute_venn2_colors
def compute_venn2_colors(set_colors):
'''
Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 3 elements, providing colors for regions (10, 01, 11).
>>> compute_venn2_colors(('r', 'g'))
(array([ 1., 0., 0.]), array([ 0. , 0.5, 0. ]), array([ 0.7 , 0.35, 0. ]))
'''
ccv = ColorConverter()
base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]))
开发者ID:alexanderwhatley,项目名称:matplotlib-venn,代码行数:10,代码来源:_venn2.py
示例16: _plot_ribbon_using_bezier
def _plot_ribbon_using_bezier(ax, zorder, points1, points2, color1="gray",
color2="gray", lw=1):
""" Draw ribbon for alluvial diagram (see plot_alluvial)
Parameters
----------
ax : a matplotlib.axes object
zorder : float
the zorder for the ribbon
points1 : iterable of float tuples
the points, which determine the first line of the Bezier ribbon
points2 : iterable of float tuples
the points, which determine the second line of the Bezier ribbon
color1 : a matplotlib compliant color definition
color for the left side of the ribbon
color1 : a matplotlib compliant color definition
color for the right side of the ribbon
lw : float
linewidth for the bezier borders
"""
cc = ColorConverter()
color1 = np.array(cc.to_rgba(color1))
color2 = np.array(cc.to_rgba(color2))
tRange = np.linspace(0, 1, 100)
xpointsList = []
ypointsList = []
for points in [points1, points2]:
points = np.array(points)
p1 = points[0]
p2 = points[1]
p3 = points[2]
p4 = points[3]
allPoints = (p1[:, np.newaxis] * (1 - tRange) ** 3 + p2[:, np.newaxis]
* (3 * (1 - tRange) ** 2 * tRange) + p3[:, np.newaxis] *
(3 * (1 - tRange) * tRange ** 2) + p4[:, np.newaxis] *
tRange ** 3)
xpoints = allPoints[0]
xpointsList.append(xpoints)
ypoints = allPoints[1]
ypointsList.append(ypoints)
ax.plot(xpoints, ypoints, "0.85", lw=lw, zorder=zorder + 0.5)
xpoints = xpointsList[0]
if (mpl.colors.colorConverter.to_rgba_array(color1) ==
mpl.colors.colorConverter.to_rgba_array(color2)).all():
ax.fill_between(xpoints, ypointsList[0], ypointsList[1], lw=lw,
facecolor=color1, edgecolor=color1, zorder=zorder)
else:
for i in range(len(tRange) - 1):
#mean = (tRange[i]+tRange[i+1])*0.5
xnow = np.mean(xpoints[i:i + 2])
norm_mean = (xnow - xpoints[0]) / (xpoints[-1] - xpoints[0])
color = color1 * (1 - norm_mean) + color2 * norm_mean
ax.fill_between(xpoints[i:i + 2], ypointsList[0][i:i + 2],
ypointsList[1][i:i + 2], lw=lw, facecolor=color,
edgecolor=color, zorder=zorder)
开发者ID:CxAalto,项目名称:verkko,代码行数:55,代码来源:alluvial.py
示例17: _parse_colour
def _parse_colour(x):
if isinstance(x, basestring):
from matplotlib.colors import ColorConverter
c = ColorConverter()
x = c.to_rgb(x)
if isinstance(x, (tuple, list)):
# Assume we have a floating point rgb
if any(a <= 1.0 for a in x):
x = [int(a * 255) for a in x]
return tuple(x)
开发者ID:dvdm,项目名称:menpo,代码行数:11,代码来源:rasterize.py
示例18: compute_venn3_colors
def compute_venn3_colors(set_colors):
'''
Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111).
>>> compute_venn3_colors(['r', 'g', 'b'])
(array([ 1., 0., 0.]),..., array([ 0.4, 0.2, 0.4]))
'''
ccv = ColorConverter()
base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]), base_colors[2],
mix_colors(base_colors[0], base_colors[2]), mix_colors(base_colors[1], base_colors[2]), mix_colors(base_colors[0], base_colors[1], base_colors[2]))
开发者ID:alexanderwhatley,项目名称:matplotlib-venn,代码行数:11,代码来源:_venn3.py
示例19: colorMask
def colorMask(v1, v2):
cc = ColorConverter()
mask = []
for i in range(len(v1)):
if v1[i] == v2[i]:
mask.append(cc.to_rgb("black"))
elif v1[i] < v2[i]:
mask.append(cc.to_rgb("red"))
else:
mask.append(cc.to_rgb("blue"))
return mask
开发者ID:ekeijl,项目名称:BeAT,代码行数:11,代码来源:graph.py
示例20: set_legend_to_bw
def set_legend_to_bw(leg, style, colormap, line_style='continuous'):
"""
Takes the figure legend and converts it to black and white. Note that
it currently only converts lines to black and white, other artist
intances are currently not being supported, and might cause errors or
other unexpected behavior.
Parameters
----------
leg : legend
style : {GREYSCALE, HATCHING}
colormap : dict
mapping of color to B&W rendering
line_style: str
linestyle to use for converting, can be continuous, black
or None
# TODO:: None is strange as a value, and should be field based, see
# set_ax_lines_bw
"""
color_converter = ColorConverter()
if leg:
if isinstance(leg, list):
leg = leg[0]
for element in leg.legendHandles:
if isinstance(element, mpl.collections.PathCollection):
rgb_orig = color_converter.to_rgb(element._facecolors[0])
new_color = color_converter.to_rgba(colormap[rgb_orig]['fill'])
element._facecolors = np.array((new_color,))
elif isinstance(element, mpl.patches.Rectangle):
rgb_orig = color_converter.to_rgb(element._facecolor)
if style==HATCHING:
element.update({'alpha':1})
element.update({'facecolor':'none'})
element.update({'edgecolor':'black'})
element.update({'hatch':colormap[rgb_orig]['hatch']})
elif style==GREYSCALE:
ema_logging.info(colormap.keys())
element.update({'facecolor':colormap[rgb_orig]['fill']})
element.update({'edgecolor':colormap[rgb_orig]['fill']})
else:
line = element
orig_color = line.get_color()
line.set_color('black')
if not line_style=='continuous':
line.set_dashes(colormap[orig_color]['dash'])
line.set_marker(colormap[orig_color]['marker'])
line.set_markersize(MARKERSIZE)
开发者ID:JamesPHoughton,项目名称:EMAworkbench,代码行数:53,代码来源:b_and_w_plotting.py
注:本文中的matplotlib.colors.ColorConverter类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论