本文整理汇总了Python中matplotlib.colors.hex2color函数的典型用法代码示例。如果您正苦于以下问题:Python hex2color函数的具体用法?Python hex2color怎么用?Python hex2color使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hex2color函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_color_as_rgba_f
def get_color_as_rgba_f(color):
color_dev = get_color_dev(color)
a = 1.
if color_dev == 'name':
hex_color = COLORS[color]
rgbf = mpl_colors.hex2color(hex_color)
elif color_dev == 'hex':
rgbf = mpl_colors.hex2color(color[:7])
if len(color) > 7:
a = int(color[-2:], 16) / 255.
elif color_dev == 'rgb':
rgbf = parse_color_to_mpl_color(color)
elif color_dev == 'rgba':
rgbaf = parse_color_to_mpl_color(color)
a = rgbaf[-1]
rgbf = rgbaf[:3]
elif color_dev == 'rgbF':
rgbf = parse_color_to_mpl_color(color)
elif color_dev == 'rgbaF':
rgbaf = parse_color_to_mpl_color(color)
rgbf = rgbaf[:3]
a = rgbaf[-1]
else:
return None
rgbaf = tuple(list(rgbf) + [a])
return rgbaf
示例2: drawCar
def drawCar(car):
myCoordinates=car.coordinates
x_coor=myCoordinates.x
y_coor=myCoordinates.y
y_coor = y_coor*ROAD_SECTION_HEIGHT
x_coor = x_coor*ROAD_SECTION_WIDTH
enable_stroke()
set_stroke_width(2)
if (car.wantsToPark):
color = colors.hex2color(Theme.Car_Parking)
set_fill_color(color[0],color[1],color[2])
set_stroke_color(color[0],color[1],color[2])
else:
color = colors.hex2color(Theme.Car_Done)
set_fill_color(color[0],color[1],color[2])
set_stroke_color(color[0],color[1],color[2])
if(car.direction == Direction.North):
x_coor = x_coor+(ROAD_SECTION_WIDTH/2)+(ROAD_SECTION_WIDTH/5)
y_coor = y_coor + (ROAD_SECTION_HEIGHT/2)
elif(car.direction == Direction.South):
x_coor = x_coor+(ROAD_SECTION_WIDTH/2)-(ROAD_SECTION_WIDTH/5)
y_coor = y_coor + (ROAD_SECTION_HEIGHT/2)
elif(car.direction == Direction.West):
y_coor = y_coor+(ROAD_SECTION_HEIGHT/2)+(ROAD_SECTION_HEIGHT/5)
x_coor = x_coor + (ROAD_SECTION_WIDTH/2)
elif(car.direction == Direction.East):
y_coor = y_coor+(ROAD_SECTION_HEIGHT/2)-(ROAD_SECTION_HEIGHT/5)
x_coor = x_coor + (ROAD_SECTION_WIDTH/2)
draw_circle(x_coor,y_coor,ROAD_SECTION_WIDTH/4)
disable_stroke()
示例3: interpolatecolour
def interpolatecolour(locolour, hicolour, value):
acolour = 0.0, 0.0, 0.0
zcolour = 1.0, 1.0, 1.0
if type(locolour) == str and locolour.startswith("#"):
acolour = cols.hex2color(locolour)
elif type(locolour) == list and all(isinstance(x, float) for x in locolour):
acolour = locolour[0], locolour[1], locolour[2]
elif type(locolour) == np.ndarray and locolour.dtype == np.float64:
acolour = float(locolour[0]), float(locolour[1]), float(locolour[2])
else:
raise ValueError(
"Couldn't make sense of locolour value, needs to be hexadecimal notation with '#', or list of floats, or numpy ndarray."
)
if type(hicolour) == str and hicolour.startswith("#"):
zcolour = cols.hex2color(hicolour)
elif type(hicolour) == list and all(isinstance(x, float) for x in locolour):
zcolour = hicolour[0], hicolour[1], hicolour[2]
elif type(hicolour) == np.ndarray and hicolour.dtype == np.float64:
zcolour = float(hicolour[0]), float(hicolour[1]), float(hicolour[2])
else:
raise ValueError(
"Couldn't make sense of hicolour value, needs to be hexadecimal notation with '#', or list of floats, or numpy ndarray."
)
return (
value * (zcolour[0] - acolour[0]) + acolour[0],
value * (zcolour[1] - acolour[1]) + acolour[1],
value * (zcolour[2] - acolour[2]) + acolour[2],
)
示例4: _get_node_plot_props
def _get_node_plot_props(G, node_class=None, max_energy=None, active_node_color=None, active_edge_color=None,
dead_node_color=None):
"""
`node_class` - Generic | Internal | Sensory | Motor
`node_size` - proportional to the sum of the presynaptic connections it makes with other nodes.
`node_colors` - function of excitatory/inhibitory, energy_value, firing/inactive
"""
cm = CMAP_DIFF # Shade from red (inhibitory) to green (excitatory)
nodes = G.nodes(node_class)
adj_matrix = nx.adjacency_matrix(G)
node_pos = nx.get_node_attributes(G.subgraph(nodes), 'pos')
edge_width = np.array([d['weight'] for (u, v, d) in G.edges(data=True) if u in nodes])
firing_nc = colors.hex2color(active_node_color) if active_node_color is not None \
else list(colors.hex2color(RENDER_NODE_PROPS['Firing']['node_face_color']))
dead_nc = colors.hex2color(dead_node_color) if dead_node_color is not None \
else list(colors.hex2color(RENDER_NODE_PROPS['Dead']['node_face_color']))
_ = firing_nc.append(1.)
_ = dead_nc.append(1.)
node_colors = _get_node_colors(G, cm, node_class=node_class, max_energy=max_energy, firing_node_color=firing_nc,
dead_node_color=dead_nc)
if node_class is not None:
min_ns, max_ns = RENDER_NODE_PROPS[node_class]['min_node_size'], RENDER_NODE_PROPS[node_class]['max_node_size']
node_shape = RENDER_NODE_PROPS[node_class]['shape']
node_size = np.array([np.maximum(adj_matrix[i].sum(), .01) for i, n_id in enumerate(G.nodes())
if G.node[n_id]['node_class'] == node_class]) # proportional to the number of connections
else:
node_shape, node_size = RENDER_NODE_PROPS['Default']['shape'], adj_matrix.sum(axis=1)
min_ns, max_ns = RENDER_NODE_PROPS['Default']['min_node_size'], RENDER_NODE_PROPS['Default']['max_node_size']
node_size = min_ns + (max_ns - min_ns) * (node_size - node_size.min()) / (node_size.max() - node_size.min()) \
if node_size.max() > node_size.min() else max_ns * np.ones_like(node_size)
return node_pos, node_colors, node_shape, node_size, edge_width
示例5: ch_color
def ch_color(x, ch=1., alpha=None):
"""
Modify color applying a multiplier in every channel, or setting an alpha value
:param str or iterator x: 3/4 channel normalized color (0->1. * 3/4 ch) or hex color
:param float ch: change coefficient
:param float alpha: desired alpha value
:return: modified color
:rtype: tuple
"""
if type(x) is str:
if x.startswith('#'):
x = hex2color(x)
elif len(x) == 6:
x = hex2color('#{}'.format(x))
else:
raise ValueError('ch_color: Not a valid color for change: {}, type={}'.format(x, type(x)))
new_c = [max(0, min(1., ch * c)) for c in x]
if alpha is not None:
if len(x) == 4:
new_c[3] = alpha
return tuple(new_c)
else:
return tuple(new_c + [alpha])
return tuple(new_c)
示例6: setup_plot
def setup_plot(self):
gs = GridSpec(1, 2, width_ratios=[9.5, 0.5])
self.axes = self.figure.add_subplot(gs[0], projection='3d')
numformatter = ScalarFormatter(useOffset=False)
timeFormatter = DateFormatter("%H:%M:%S")
self.axes.set_xlabel("Frequency (MHz)")
self.axes.set_ylabel('Time')
self.axes.set_zlabel('Level (dB)')
self.axes.w_xaxis.set_pane_color(hex2color(self.settings.background))
self.axes.w_yaxis.set_pane_color(hex2color(self.settings.background))
self.axes.w_zaxis.set_pane_color(hex2color(self.settings.background))
self.axes.xaxis.set_major_formatter(numformatter)
self.axes.yaxis.set_major_formatter(timeFormatter)
self.axes.zaxis.set_major_formatter(numformatter)
self.axes.xaxis.set_minor_locator(AutoMinorLocator(10))
self.axes.yaxis.set_minor_locator(AutoMinorLocator(10))
self.axes.zaxis.set_minor_locator(AutoMinorLocator(10))
self.axes.set_xlim(self.settings.start, self.settings.stop)
now = time.time()
self.axes.set_ylim(epoch_to_mpl(now), epoch_to_mpl(now - 10))
self.axes.set_zlim(-50, 0)
self.bar = self.figure.add_subplot(gs[1])
norm = Normalize(vmin=-50, vmax=0)
self.barBase = ColorbarBase(self.bar, norm=norm,
cmap=cm.get_cmap(self.settings.colourMap))
self.barBase.set_label('Level (dB)')
示例7: add_pie_chart
def add_pie_chart(summary_counts, sample_name, fig, graph_i, graphs_num):
"""
Add a pie chart to a Wild Life of Our Homes data visualization figure.
"""
ax = fig.add_axes([0.25, 0.02 + (0.98 / graphs_num) * graph_i, 0.50, (0.98 / graphs_num)])
ax.set_aspect(1)
color_set = [c for c in colors.cnames if
sum(colors.hex2color(colors.cnames[c])) < 2.5 and
sum(colors.hex2color(colors.cnames[c])) > 1]
random.shuffle(color_set)
color_set = color_set[0:len(summary_counts)]
pie_chart = ax.pie(
[sc[1] for sc in summary_counts],
labels=['/'.join(sc[0]) for sc in summary_counts],
labeldistance=1.05,
pctdistance=0.67,
colors=color_set,
autopct='%1.1f%%')
center_circle = plt.Circle((0, 0), 0.75, color='white', fc='white')
fig = plt.gcf()
fig.gca().add_artist(center_circle)
for pie_wedge in pie_chart[0]:
pie_wedge.set_edgecolor('white')
for t in pie_chart[1]:
t.set_size('smaller')
for t in pie_chart[2]:
t.set_size('x-small')
ax.set_title(sample_name)
ax.text(-0.6, -1.35, 'Groups with less than 0.4% not depicted.')
示例8: get_colors
def get_colors(n, first='#1f77b4', last='#d62728'):
"""Return a list of colors interpolating between the first and last.
The function accepts both strings representing hex colors and tuples
containing RGB values, which must be between 0 and 1.
Parameters
----------
n : int
Number of colors to be generated.
first : str or tuple of float
First color in the list (defaults to Matplotlib default blue).
last : str, tuple
Last color in the list(defaults to Matplotlib default red).
Returns
-------
colors : list
A list of strings containing hex colors
"""
if not isinstance(first, tuple):
first = hex2color(first)
if not isinstance(last, tuple):
last = hex2color(last)
return [rgb2hex((first[0]+(last[0]-first[0])*i/(n-1),
first[1]+(last[1]-first[1])*i/(n-1),
first[2]+(last[2]-first[2])*i/(n-1))) for i in range(n)]
示例9: hex3colormap
def hex3colormap(hex1, hex2, hex3):
from matplotlib.colors import hex2color
from matplotlib.colors import LinearSegmentedColormap
some_name = 'some_name'
[hex1r, hex1g, hex1b] = hex2color(hex1)
[hex2r, hex2g, hex2b] = hex2color(hex2)
[hex3r, hex3g, hex3b] = hex2color(hex3)
cdict = {'red': ((0.0, hex1r, hex1r),
(0.5, hex2r, hex2r),
(1.0, hex3r, hex3r)),
'green': ((0.0, hex1g, hex1g),
(0.5, hex2r, hex2r),
(1.0, hex3g, hex3g)),
'blue': ((0.0, hex1b, hex1b),
(0.5, hex2r, hex2r),
(1.0, hex3b, hex3b))
}
colormapname2 = LinearSegmentedColormap(some_name, cdict)
return colormapname2
示例10: output_graph
def output_graph(coord, centroids, clusters, num_clusters):
x_coord = []
y_coord = []
# Divide the coordinates into x and y coordiantes
for i in coord:
x_coord.append(i[0])
y_coord.append(i[1])
np_x = np.asarray(x_coord)
np_y = np.asarray(y_coord)
colors_option = []
for i in range(num_clusters):
colors_option.append('#'+'%06X' % random.randint(0, 0xFFFFFF))
np_centroids = np.asarray(centroids)
while(num_clusters):
for i in range(len(coord)):
if(clusters[i] == num_clusters-1):
plt.scatter(np_x[i],np_y[i],color=colors.hex2color(colors_option[num_clusters-1]),s=6,alpha=0.5)
#plot the centroids
plt.scatter(np_centroids[num_clusters-1][0],np_centroids[num_clusters-1][1],
color=colors.hex2color(colors_option[num_clusters-1]), marker='>', s=150)
num_clusters = num_clusters - 1
plt.show()
示例11: test_get_random_color
def test_get_random_color(self):
''' Should return HEX code of random color '''
c0 = get_random_color()
c1 = get_random_color(c0)
c2 = get_random_color(c1, 300)
self.assertEqual(type(hex2color(c0)), tuple)
self.assertEqual(type(hex2color(c1)), tuple)
self.assertEqual(type(hex2color(c2)), tuple)
示例12: get_line_color
def get_line_color(ix, modifier=None):
colour = _lines_colour_cycle[ix]
if modifier=='dark':
return tuple(c/2 for c in colors.hex2color(colour))
elif modifier=='light':
return tuple(1-(1-c)/2 for c in colors.hex2color(colour))
elif modifier is not None:
raise NotImplementedError(modifier)
return colors.hex2color(colour)
示例13: main
def main():
allX = []
allY = []
centroidsX = []
centroidsY = []
cluster = []
oldCluster = []
colorArray = []
stop = False
maxIteration = 100
iterations = 0
numOfClusters = int(sys.argv[1])
filename = str(sys.argv[2])
allX, allY = readFile(filename)
maxX = max(allX)
maxY = max(allY)
minX = min(allX)
minY = min(allY)
# initials centroids
centroidsX, centroidsY = findRandomCentroids(numOfClusters, minX, maxX, minY, maxY)
# labels each point with appropriate centroid
cluster = assignCentroids(allX, allY, centroidsX, centroidsY)
# continuously looking for new cluster and new centroids until convergence
while (stop == False):
oldCluster = cluster
centroidsX, centroidsY = findCentroids(numOfClusters, cluster, allX, allY)
cluster = assignCentroids(allX, allY, centroidsX, centroidsY)
iterations += 1
if ((oldCluster == cluster) or (iterations == maxIteration)):
stop = True
x = np.asarray(allX)
y = np.asarray(allY)
centX = np.asarray(centroidsX)
centY = np.asarray(centroidsY)
for i in range(numOfClusters):
colorArray.append('#'+'%06X' % random.randint(0, 0xFFFFFF))
#plt.scatter(x, y,color=colors.hex2color(colorArray[0]), s=1, alpha=0.5)
for j in range(len(centX)):
plt.scatter(centX[j], centY[j], color = colors.hex2color(colorArray[j]))
for i in range(len(cluster)):
if (cluster[i] == j):
plt.scatter(x[i], y[i], color=colors.hex2color(colorArray[j]), s=5, alpha=0.5)
plt.show()
示例14: __init__
def __init__(self, pdb_object, structure_name, residues_of_interest = [], label_all_residues_of_interest = False, **kwargs):
'''The chain_seed_color kwarg can be either:
- a triple of R,G,B values e.g. [0.5, 1.0, 0.75] where each value is between 0.0 and 1.0;
- a hex string #RRGGBB e.g. #77ffaa;
- a name defined in the predefined dict above e.g. "aquamarine".
'''
self.pdb_object = pdb_object
self.structure_name = structure_name
self.add_residues_of_interest(residues_of_interest)
self.label_all_residues_of_interest = label_all_residues_of_interest
self.chain_colors = kwargs.get('chain_colors') or {}
# Set up per-chain colors
try:
if not self.chain_colors and kwargs.get('chain_seed_color'):
chain_seed_color = kwargs.get('chain_seed_color')
if isinstance(chain_seed_color, str) or isinstance(chain_seed_color, unicode):
chain_seed_color = str(chain_seed_color)
if chain_seed_color.startswith('#'):
if len(chain_seed_color) != 7:
chain_seed_color = None
else:
trpl = predefined.get(chain_seed_color)
chain_seed_color = None
if trpl:
chain_seed_color = mpl_colors.rgb2hex(trpl)
elif isinstance(chain_seed_color, list) and len(chain_seed_color) == 3:
chain_seed_color = mpl_colors.rgb2hex(chain_seed_color)
if chain_seed_color.startswith('#') and len(chain_seed_color) == 7:
# todo: We are moving between color spaces multiple times so are probably introducing artifacts due to rounding. Rewrite this to minimize this movement.
chain_seed_color = chain_seed_color[1:]
hsl_color = colorsys.rgb_to_hls(int(chain_seed_color[0:2], 16)/255.0, int(chain_seed_color[2:4], 16)/255.0, int(chain_seed_color[4:6], 16)/255.0)
chain_seed_hue = int(360.0 * hsl_color[0])
chain_seed_saturation = max(0.15, hsl_color[1]) # otherwise some colors e.g. near-black will not yield any alternate colors
chain_seed_lightness = max(0.15, hsl_color[2]) # otherwise some colors e.g. near-black will not yield any alternate colors
min_colors_in_wheel = 4 # choose at least 4 colors - this usually results in a wider variety of colors and prevents clashes e.g. given 2 chains in both mut and wt, wt seeded with blue, and mut seeded with yellow, we will get a clash
chain_ids = sorted(pdb_object.atom_sequences.keys())
# Choose complementary colors, respecting the original saturation and lightness values
chain_colors = ggplot_color_wheel(max(len(chain_ids), min_colors_in_wheel), start = chain_seed_hue, saturation_adjustment = None, saturation = chain_seed_saturation, lightness = chain_seed_lightness)
assert(len(chain_colors) >= len(chain_ids))
self.chain_colors = {}
for i in xrange(len(chain_ids)):
self.chain_colors[chain_ids[i]] = str(list(mpl_colors.hex2color('#' + chain_colors[i])))
# Force use of the original seed as this may have been altered above in the "= max(" statements
self.chain_colors[chain_ids[0]] = str(list(mpl_colors.hex2color('#' + chain_seed_color)))
except Exception, e:
print('An exception occurred setting the chain colors. Ignoring exception and resuming with default colors.')
print(str(e))
print(traceback.format_exc())
示例15: mt_plot
def mt_plot():
"""
Return a moment tensor image.
"""
formats = {
"png": "image/png",
"svg": "image/svg+xml"
}
args = flask.request.args
m_rr = float(args["m_rr"])
m_tt = float(args["m_tt"])
m_pp = float(args["m_pp"])
m_rt = float(args["m_rt"])
m_rp = float(args["m_rp"])
m_tp = float(args["m_tp"])
focmec = (m_rr, m_tt, m_pp, m_rt, m_rp, m_tp)
# Allow hexcolors.
color = args.get("color", "red")
try:
hexcolor = "#" + color
hex2color(hexcolor)
color = hexcolor
except ValueError:
pass
size = int(args.get("size", 32))
lw = float(args.get("lw", 1))
format = args.get("format", "png")
if format not in formats.keys():
flask.abort(500)
dpi = 100
fig = plt.figure(figsize=(float(size) / float(dpi),
float(size) / float(dpi)),
dpi=dpi)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
bb = Beach(focmec, xy=(0, 0), width=200, linewidth=lw, facecolor=color)
ax.add_collection(bb)
ax.set_xlim(-105, 105)
ax.set_ylim(-105, 105)
temp = io.BytesIO()
plt.savefig(temp, format=format, dpi=dpi, transparent=True)
plt.close(fig)
plt.close("all")
temp.seek(0, 0)
return flask.send_file(temp, mimetype=formats[format],
add_etags=False,
attachment_filename="mt.%s" % format)