本文整理汇总了Python中matplotlib.colors.hex2color函数的典型用法代码示例。如果您正苦于以下问题:Python hex2color函数的具体用法?Python hex2color怎么用?Python hex2color使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hex2color函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:SharpLu,项目名称:Sympathy-for-data-benchmark,代码行数:27,代码来源:colors.py
示例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()
开发者ID:patxu,项目名称:parking_sim,代码行数:35,代码来源:run.py
示例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],
)
开发者ID:jreades,项目名称:SpatialAnalysis,代码行数:31,代码来源:Basemap.py
示例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
开发者ID:hurtb,项目名称:pyBrainNetSim,代码行数:34,代码来源:viewers.py
示例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)
开发者ID:azogue,项目名称:enerpi,代码行数:26,代码来源:enerplot.py
示例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)')
开发者ID:vlslv,项目名称:RTLSDR-Scanner,代码行数:29,代码来源:plot3d.py
示例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.')
开发者ID:PersonalGenomesOrg,项目名称:open-humans-data-processing,代码行数:29,代码来源:visualization.py
示例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)]
开发者ID:nexpy,项目名称:nexpy,代码行数:27,代码来源:utils.py
示例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
开发者ID:chennipman,项目名称:MCLS,代码行数:27,代码来源:hex2colormap.py
示例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()
开发者ID:linsiqi1,项目名称:K-Means-Clustering,代码行数:30,代码来源:Clustering.py
示例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)
开发者ID:scollis,项目名称:nansat,代码行数:9,代码来源:test_tools.py
示例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)
开发者ID:QUVA-Lab,项目名称:artemis,代码行数:9,代码来源:pyplot_plus.py
示例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()
开发者ID:yzhang27,项目名称:KMeansClustering,代码行数:56,代码来源:Clustering.py
示例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())
开发者ID:Kortemme-Lab,项目名称:klab,代码行数:56,代码来源:colors.py
示例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)
开发者ID:Debesys,项目名称:LASIF,代码行数:56,代码来源:server.py
示例16: plot_regions
def plot_regions(projection, regions_filepath, regions_dirpath, title,
lat_range=ALL_LAT_RANGE, long_range=ALL_LONG_RANGE):
"""
Returns
-------
fig, ax
"""
fig, ax = plt.subplots()
ax.set_title(title)
# get region economic prosperity levels
econ_levels = []
with open(regions_filepath) as file:
for line in file:
_, econ_level = line.strip().split("|")
econ_levels.append(int(econ_level))
# setup coloring
ax.set_axis_bgcolor("#BFECFF") # ocean blue
# color map
econ_cmap = colors.LinearSegmentedColormap.from_list(
'econ_colors', [colors.hex2color("#DDFF28"), colors.hex2color("#D70A0A")])
sm = plt.cm.ScalarMappable(cmap=econ_cmap, norm=plt.Normalize(vmin=1, vmax=7))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
cbar = fig.colorbar(sm, ticks=[7, 6, 5, 4, 3, 2, 1])
cbar.set_label("Economic level", rotation=270)
cbar.ax.get_yaxis().labelpad = 15
# optimization
norm = 1/ECONOMIC_LEVELS
# walk through regions directory and plot all the regions
_, regions_dirs, _ = next(os.walk(regions_dirpath))
regions_dirs = [d for d in regions_dirs if d[0] != "."] # remove hidden subdirectories
for reg_dir in regions_dirs:
root, _, files = next(os.walk(os.path.join(regions_dirpath, reg_dir)))
files = [f for f in files if f[0] != "."] # remove hidden files
for file in files:
if file.startswith("landshape"):
landshape_coords = get_landshape_coords(os.path.join(root, file))
elif file.startswith("landparts"):
landparts = get_landparts(os.path.join(root, file))
if lat_range != ALL_LAT_RANGE or long_range != ALL_LONG_RANGE:
landshape_coords, landparts = filter_landshape_landparts(
landshape_coords, landparts, lat_range, long_range)
# if everything was filtered out, continue to next region
if len(landshape_coords) <= 2:
continue
color = econ_cmap(econ_levels[int(reg_dir)] * norm)
color = colors.rgb2hex(color)
plot_landparts(ax, projection, landshape_coords, landparts, color)
fig.tight_layout()
return fig, ax
开发者ID:kerryz,项目名称:world_map_visualization,代码行数:55,代码来源:map_projections.py
示例17: runGraphics
def runGraphics():
color = colors.hex2color(Color.White)
set_clear_color(color[0],color[1],color[2])
clear()
#Grass
disable_stroke()
color = colors.hex2color(Theme.Background)
set_fill_color(color[0],color[1],color[2])
draw_rectangle(0,0,CANVAS_WIDTH,CANVAS_HEIGHT)
while not window_closed():
numDriving = len([car for car in carList if car.parkingSpot == None])
for i in range(numDriving):
env.step()
if numDriving == 0:
env.step()
for road in cityMap.roads:
for roadSection in road.roadSections:
drawRoadSection(roadSection)
for car in carList:
drawCar(car)
request_redraw()
sleep(STEP_LENGTH)
if is_key_pressed("p"):
while 1:
if is_key_pressed("r"):
break;
sleep(0.1)
update_progress(float(len([car for car in carList if len(car.destinations) == 0]))/float(len(carList)))
if float(len([car for car in carList if len(car.destinations) == 0]))/float(len(carList)) > .97:
sys.stdout.write("\n")
print("Finished Simulation!")
break
fp=open(logname,"w")
fp.write("Parking Log\n")
total=0
totalAverage = 0
totalDistanceAverage = 0
for car in carList:
averageTime = (car.timeSpent / car.totalDestinations)
averageDistance = (car.distanceFrom / car.totalDestinations)
totalAverage += averageTime
totalDistanceAverage += averageDistance
total += car.timeSpent
fp.write("Car: "+str(car.getCarID())+" Total Time Spent Searching: "+str(car.timeSpent)+ " Average Time Spent Searching: " + str(averageTime) + "For an average distance from destination of: " + str(averageDistance) + "\n")
fp.write("Total Time Spent Looking for Parking by All Cars: "+str(total)+ " Average Time Spent Looking: " + str(totalAverage/len(carList)) + " Average Distance from destination: " + str(totalDistanceAverage/len(carList))+"\n")
fp.close()
sys.exit(0)
开发者ID:patxu,项目名称:parking_sim,代码行数:55,代码来源:run.py
示例18: format_progress
def format_progress(hexcolor0, hexcolor1, formstring, entry_current_page, entry_length):
ratio = 1.0 * int(entry_current_page) / int(entry_length)
# Do stuff with color diff
color0 = colors.hex2color(hexcolor0)
color1 = colors.hex2color(hexcolor1)
color_red = ratio * (color1[0] - color0[0]) + color0[0]
color_green = ratio * (color1[1] - color0[1]) + color0[1]
color_blue = ratio * (color1[2] - color0[2]) + color0[2]
color_str = colors.rgb2hex((color_red, color_green, color_blue))
return progresstemplate_row.format(progresscolor=color_str,
current_page = int(entry_current_page),
length=int(entry_length))
开发者ID:cefyr,项目名称:mneme,代码行数:12,代码来源:indexframe.py
示例19: draw_networkx
def draw_networkx(G, pos=None, ax=None, max_e=None, plot_active=True, active_node_color=None, **kwargs):
internal_color, internal_ecolor, internal_alpha = '#FCDC79', '#C79500', 0.5
overall_color, overall_ecolor, overall_alpha = '#A1A1A1', '#050505', 0.2
if ax is None:
fig, ax = plt.subplots()
for node_class in RENDER_NODE_PROPS.iterkeys():
if node_class in ['Default', 'Active', 'Dead', 'Firing']:
continue
gs = G.subgraph(G.nodes(node_class)).copy()
node_pos, node_colors, node_shape, node_size, edge_width = _get_node_plot_props(gs, node_class, max_energy=max_e)
nx.draw_networkx_nodes(gs, node_pos, node_color=node_colors, node_shape=node_shape, node_size=node_size, ax=ax, **kwargs)
node_pos, node_colors, node_shape, node_size, edge_width = _get_node_plot_props(G, max_energy=max_e)
if pos is not None:
node_pos = pos
nx.draw_networkx_edges(G, node_pos, width=edge_width, alpha=0.2, ax=ax) # draw edges
i_subg = G.subgraph(G.nodes('Internal'))
m_subg = G.subgraph(G.nodes('Motor'))
s_subg = G.subgraph(G.nodes('Sensory'))
# Add patches for the entire network and internal nodes
ax.add_patch(
create_axes_patch(nx.get_node_attributes(G, 'pos').values(), scale=1.2, facecolor=overall_color,
edgecolor=overall_ecolor, alpha=overall_alpha))
ax.add_patch(
create_axes_patch(nx.get_node_attributes(i_subg, 'pos').values(), scale=1.2, facecolor=internal_color,
edgecolor=internal_ecolor, alpha=internal_alpha))
# Add arrows indicating force direction
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']))
arrow_scale = 1
for m_id, attr in m_subg.node.iteritems():
arr_cl = firing_nc if G.is_node_firing(m_id) else 'k'
if len(attr['force_direction']) == 1:
dx, dy = attr['force_direction'][0], 0.
else:
dx, dy = attr['force_direction']
ax.arrow(attr['pos'][0], attr['pos'][1], dx * arrow_scale, dy * arrow_scale,
head_width=1, head_length=np.linalg.norm(attr['force_direction'])/2, fc='k', ec=arr_cl)
labels = nx.draw_networkx_labels(G, pos=node_pos, font_color='w')
xlim, ylim = ax.get_xlim(), ax.get_ylim()
ax.set_xlim([xlim[0]-arrow_scale, xlim[1]+arrow_scale])
ax.set_ylim([ylim[0] - arrow_scale, ylim[1] + arrow_scale])
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
# ax.set_title("%s Network @ t:%d" %("ID", 0), {'fontsize': 10})
ax.set_aspect('equal')
ax.set(**kwargs)
return ax
开发者ID:hurtb,项目名称:pyBrainNetSim,代码行数:50,代码来源:viewers.py
示例20: name2color
def name2color(name):
"""Return the 3-element RGB array of a given color name."""
if '#' in name:
h = name
else:
h = co.cnames[name].lower()
return co.hex2color(h)
开发者ID:zkbt,项目名称:zachopy,代码行数:7,代码来源:color.py
注:本文中的matplotlib.colors.hex2color函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论