我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用matplotlib.colors.ColorConverter()。
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]))
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]))
def __init__(self, line_width=0.002, alpha = 1.0, color='black'): from matplotlib.colors import ColorConverter conv = ColorConverter() PlotCallback.__init__(self) self.line_width = line_width self.alpha = alpha self.color = (np.array(conv.to_rgb(color)) * 255).astype("uint8")
def set_bgcolor(self, color, alpha=1.0): self._ax.set_axis_bgcolor(ColorConverter().to_rgba(color, alpha)) self.draw()
def draw(self): color, alpha = self._ax.get_axis_bgcolor(), self._ax.get_alpha() self._ax.set_axis_bgcolor(mpl.rcParams['figure.facecolor']) self._ax.draw_artist(self._ax.patch) self._ax.set_axis_bgcolor(ColorConverter().to_rgba(color, alpha)) self._ax.draw_artist(self._ax.patch) self._ax.draw_artist(self._text_box) self._fig.canvas.update() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
def diverge_map(low=(239/255., 65/255., 50/255.), high=(39/255., 184/255., 148/255.)): """Low and high are colors that will be used for the two ends of the spectrum. they can be either color strings or rgb color tuples """ c = mcolors.ColorConverter().to_rgb if isinstance(low, basestring): low = c(low) if isinstance(high, basestring): high = c(high) return make_colormap([low, c('white'), 0.5, c('white'), high])
def plot_probability_of_activation(G, pos, Q): import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap import matplotlib.colors as mcolors def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mcolors.LinearSegmentedColormap('CustomMap', cdict,5000) def get_activation_probability(Q, N): Acti = [0.0]*N for key in Q: acti = [int(u) for u in list(key)] for i,ac in enumerate(acti): Acti[i] += ac*Q[key] return Acti c = mcolors.ColorConverter().to_rgb rvb = make_colormap([c('#d0151d'), c('#f88d59'), 0.2, c('#f88d59') , c('#fbe18f'), 0.4, c('#fbe18f') , c('#e2f3f8'), 0.6,c('#e2f3f8') , c('#96bfdb'), 0.8, c('#96bfdb'), c('#4d74b5')]) node_color = get_activation_probability(Q,len(G.node)) fig = plt.figure(figsize=(7,2.5),frameon=False) edges = nx.draw_networkx_nodes(G,pos=pos,width=6, node_size=1000, linewidths=4,edge_color="#BFBFBF",node_color=node_color,with_labels=False,cmap=rvb) nx.draw_networkx_edges(G,pos=pos,width=4,linewidths=20,edge_color="black") # # plt.xlim([-0.5,0.6]) # plt.ylim([-0.3,0.3]) ax = plt.gca() ax.axis('off') plt.savefig("./test.png") plt.colorbar(edges) plt.savefig("./test_withcolorbar.png") # plt.savefig("./plot/network_activation_3.pdf") # plt.show() return
def plot_probability_of_activation(G, pos, Q): import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap import matplotlib.colors as mcolors def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict['red'].append([item, r1, r2]) cdict['green'].append([item, g1, g2]) cdict['blue'].append([item, b1, b2]) return mcolors.LinearSegmentedColormap('CustomMap', cdict,5000) def get_activation_probability(Q, N): Acti = [0.0]*N for key in Q: acti = [int(u) for u in list(key)] for i,ac in enumerate(acti): Acti[i] += ac*Q[key] return Acti c = mcolors.ColorConverter().to_rgb rvb = make_colormap([c('#4d74b5'),c('#96bfdb'), 0.2, c('#96bfdb') , c('#e2f3f8'), 0.4, c('#e2f3f8') , c('#fbe18f'), 0.6, c('#fbe18f') , c('#f88d59'), 0.8, c('#f88d59'), c('#d0151d')]) node_color = get_activation_probability(Q,len(G.node)) fig = plt.figure(figsize=(5,3),frameon=False) nodes = nx.draw_networkx_nodes(G,pos=pos,width=1, node_size=1200, linewidths=4, edge_color="black",node_color=node_color,with_labels=False,cmap=rvb) nodes.set_edgecolor('black') nx.draw_networkx_edges(G,pos=pos,width=4,edge_color="black") plt.xlim([-0.3,3]) plt.ylim([-0.3,1.2]) ax = plt.gca() ax.axis('off') plt.savefig("./test.png") plt.colorbar(nodes) plt.savefig("./test_withcolorbar.png", bbox_inches='tight', pad_inches=0.1,dpi=200) # plt.savefig("./plot/network_activation_3.pdf") # plt.show() return
def make_colormap(colors): #------------------------- """ Define a new color map based on values specified in the dictionary colors, where colors[z] is the color that value z should be mapped to, with linear interpolation between the given values of z. The z values (dictionary keys) are real numbers and the values colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an html hex string, e.g. "#ff0000" for red. """ from matplotlib.colors import LinearSegmentedColormap, ColorConverter from numpy import sort z = 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): #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))] 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
def drawOn(self, canv, x, y, _sW=0): if _sW and hasattr(self,'hAlign'): from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY a = self.hAlign if a in ('CENTER','CENTRE', TA_CENTER): x = x + 0.5*_sW elif a in ('RIGHT',TA_RIGHT): x = x + _sW elif a not in ('LEFT',TA_LEFT): raise ValueError, "Bad hAlign value "+str(a) height = 0 if HAS_MATPLOTLIB: global fonts canv.saveState() canv.translate(x, y) try: width, height, descent, glyphs, \ rects, used_characters = self.parser.parse( enclose(self.s), 72, prop=FontProperties(size=self.fontsize)) for ox, oy, fontname, fontsize, num, symbol_name in glyphs: if not fontname in fonts: fonts[fontname] = fontname pdfmetrics.registerFont(TTFont(fontname, fontname)) canv.setFont(fontname, fontsize) col_conv=ColorConverter() rgb_color=col_conv.to_rgb(self.color) canv.setFillColorRGB(rgb_color[0],rgb_color[1],rgb_color[2]) canv.drawString(ox, oy, unichr(num)) canv.setLineWidth(0) canv.setDash([]) for ox, oy, width, height in rects: canv.rect(ox, oy+2*height, width, height, fill=1) except: # FIXME: report error col_conv=ColorConverter() rgb_color=col_conv.to_rgb(self.color) canv.setFillColorRGB(rgb_color[0],rgb_color[1],rgb_color[2]) canv.drawString(0,0,self.s) canv.restoreState() else: canv.saveState() canv.drawString(x, y, self.s) canv.restoreState() if self.label: log.info('Drawing equation-%s'%self.label) canv.bookmarkHorizontal('equation-%s'%self.label,0,height)
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 import ImageColor except ImportError: from PIL import ( Image, ImageFont, ImageDraw, ImageColor, ) 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(unichr(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), unichr(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