本文整理汇总了Python中matplotlib.colors.ColorConverter类的典型用法代码示例。如果您正苦于以下问题:Python ColorConverter类的具体用法?Python ColorConverter怎么用?Python ColorConverter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ColorConverter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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()
示例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
示例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})
示例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
示例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)
示例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
示例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()
示例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()
示例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()
示例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
示例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
示例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]))