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)
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
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()
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
def set_legend_to_bw(leg): """ 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. :param fig: The figure which needs to be transformed to B&W. """ color_converter = ColorConverter() colors = {} for key, value in color_converter.colors.items(): colors[value] = key if leg: if type(leg) == ListType: leg = leg[0] for element in leg.legendHandles: if isinstance(element, mpl.collections.PathCollection): rgb_orig = color_converter.to_rgb(element._facecolors[0]) origColor = colors[rgb_orig] new_color = color_converter.to_rgba(COLORMAP[origColor]['fill']) element._facecolors = np.array((new_color,)) else: line = element origColor = line.get_color() line.set_color('black') line.set_dashes(COLORMAP[origColor]['dash']) line.set_marker(COLORMAP[origColor]['marker']) line.set_markersize(MARKERSIZE)
def set_ax_polycollections_to_bw(ax): """ Take each polycollection in the axes, ax, and convert the face color to be suitable for black and white viewing. :param ax: The ax of which the polycollection needs to be transformed to B&W. TODO:: this function has a misleading name for it transforms all collection types. We need to make a decision on whether we can transform collections in general or parcel it out to separate functions for each collection class. """ color_converter = ColorConverter() colors = {} for key, value in color_converter.colors.items(): colors[value] = key 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']) a = np.asarray([new_color]) polycollection.update({'facecolors' : a}) polycollection.update({'edgecolors' : 'black'})
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
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
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
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})
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()
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
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()
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()
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
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 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
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)
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)
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
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 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)
def _set_ax_pathcollection_to_bw(collection, ax, style): 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] color = [colors.get(entry) for entry in rgb_orig] new_color = [color_converter.to_rgba(COLORMAP[entry]['fill']) for entry in color] new_color = np.asarray(new_color) collection.update({'facecolors' : new_color}) collection.update({'edgecolors' : 'black'})
def drawImpacts2D(self, x=True, y=True, z=False): # Load the dataset dataset = self.datasetManager.loadDataset(self.datasetManager.getAccuracyComplete()) plt.axis("equal") 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) if not x: plt.scatter(y, z, color=cc, marker="o", s=50) elif not y: plt.scatter(x, z, color=cc, marker="o", s=50) else: plt.scatter(x, y, color=cc, marker="o", s=50) plt.show()
def plot2(self): """ plot curves of function integrand for different beta values """ from matplotlib.collections import LineCollection from matplotlib.colors import ColorConverter colorConverter = ColorConverter() slab = SlabModel() # R is unimportant eta = linspace(0.0, 1.0, num=100) fig = P.figure(1) P.clf() # #--- subplot 1: Fixed lambda, varying beta ax1 = fig.add_subplot(2,1,1) ax1.set_xlim((0.0, 1.0)) beta = linspace(0.0, 1.0, num=10) ym = [ slab.PaulMcSpaddenIntegrand(eta, beta=b, m=3) for b in beta ] line_segments = LineCollection( [ zip(eta,y) for y in ym ], colors = [colorConverter.to_rgba(i) \ for i in ('b','g','r','c','m','y','k')] ) ax1.add_collection( line_segments, autolim=True ) ax1.autoscale_view() axhline() ax1.set_xlabel(r'$\eta\quad\quad(m=3)$') ax1.set_ylabel(r'$\mbox{erf}(\beta\eta)\sin(\lambda_m\eta)$') # #--- subplot 2: Fixed beta, varying lambda ax2 = fig.add_subplot(2,1,2) ax2.set_xlim((0.0, 1.0)) ym = [ slab.PaulMcSpaddenIntegrand(eta, beta=0.27, m=m) for m in range(10) ] line_segments = LineCollection( [ zip(eta,y) for y in ym ], colors = [colorConverter.to_rgba(i) \ for i in ('b','g','r','c','m','y','k')] ) ax2.add_collection( line_segments, autolim=True ) ax2.autoscale_view() axhline() ax2.set_xlabel(r'$\eta\quad\quad(\beta=0.27)$') ax2.set_ylabel(r'$\mbox{erf}(\beta\eta)\sin(\lambda_m\eta)$') P.show() return
def set_legend_to_bw(leg, style): """ 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} """ color_converter = ColorConverter() colors = {} for key, value in color_converter.colors.items(): colors[value] = key 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]) origColor = colors[rgb_orig] new_color = color_converter.to_rgba(COLORMAP[origColor]['fill']) element._facecolors = np.array((new_color,)) elif isinstance(element, mpl.patches.Rectangle): rgb_orig = color_converter.to_rgb(element._facecolor) c = colors[rgb_orig] if style==HATCHING: element.update({'alpha':1}) element.update({'facecolor':'none'}) element.update({'edgecolor':'black'}) element.update({'hatch':COLORMAP[c]['hatch']}) elif style==GREYSCALE: element.update({'facecolor':COLORMAP[c]['fill']}) element.update({'edgecolor':COLORMAP[c]['fill']}) else: line = element origColor = line.get_color() line.set_color('black') line.set_dashes(COLORMAP[origColor]['dash']) line.set_marker(COLORMAP[origColor]['marker']) line.set_markersize(MARKERSIZE)
def mpl_to_qt4_color(color): """ Convert a matplotlib color stirng into a PyQT4 QColor object Parameters ---------- color: String A color specification that matplotlib understands Returns ------- A QColor object representing color """ cc = ColorConverter() r, g, b = cc.to_rgb(color) return QColor(r * 255, g * 255, b * 255)
def __init__(self, panel): PlotView.__init__(self, panel) # stores the plot objects self.plots = [] self.__plot_count = 0 # self.highlighted_vertices = set() # Rename to selected_vertices self.highlighted_vertices = [] # Keeps track of the highlighted vertices index self.marker = None # Must be a matplotlib line2D object self.x_scatter_data, self.y_scatter_data = None, None # Holds the scatter data for highlighting self.poly_list = None # Holds the data for the plotted polygon self.highlight_color = "y" # Yellow is used when highlighting self.color = "#0DACFF" # The standard color for objects that are not highlighted self._color_converter = ColorConverter() self.line_collection = None # Holds the line collection data self.highlighted_lines = [] self.selected_lines = [] # stores the axis objects self.__axis = [] # matplotlib color cycle used to ensure primary and secondary axis are not displayed with the same color self.__color_cycle = color_cycle() # Used to be able to deactivate the canvas events later self._cid_press = None self._cid_release = None self._cid_scroll = None
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 fontname not 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, chr(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 _set_ax_polycollection_to_bw(collection, ax, style, colormap): '''helper function for converting a polycollection to black and white Parameters ---------- collection : polycollection ax : axes style : {GREYSCALE, HATCHING} colormap : dict mapping of color to B&W rendering ''' if style == GREYSCALE: color_converter = ColorConverter() for polycollection in ax.collections: orig_color = polycollection._original_facecolor try: mapping = colormap[orig_color] except BaseException: ema_logging.warning( 'no mapping specified for color: {}'.format(orig_color)) else: new_color = color_converter.to_rgba(mapping['fill']) new_color = np.asarray([new_color]) polycollection.update({'facecolors': new_color}) polycollection.update({'edgecolors': new_color}) elif style == HATCHING: orig_color = collection._original_facecolor try: mapping = colormap[orig_color] except BaseException: ema_logging.warning( 'no mapping specified for color: {}'.format(orig_color)) else: 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[orig_color]['hatch']) ax.add_patch(p1) p1.set_zorder(collection.get_zorder() - 0.1)
import types import nibabel import numpy as np from traits.api import HasTraits, List, Instance, Array, Bool, Dict, Range, Float, Enum, Color, Int, Str, on_trait_change, Button, DelegatesTo, Any from traitsui.api import View, Item, HGroup, Group, ImageEnumEditor, ColorEditor, TextEditor from tvtk.api import tvtk from tvtk.pyface.scene import Scene from six import string_types from matplotlib.colors import ColorConverter cc = ColorConverter() from mayavi import mlab from mayavi.core.ui import lut_manager from mayavi.core.api import PipelineBase, Source, Filter, Module from mayavi.core.ui.api import SceneEditor, MlabSceneModel, MayaviScene from . import options from . import polyutils from . import volume legend = '''[, ]:\t\tNext, Prev slice Ins:\t\tRotate view ccw PgUp:\tRotate view cw PgDn:\tScale view x up Del:\t\tScale view x down Home:\tScale view y up End:\t\tScale view y down arrows:\tMove view
def yearplot(data, year=None, how='sum', vmin=None, vmax=None, cmap='Reds', fillcolor='whitesmoke', linewidth=1, linecolor=None, daylabels=calendar.day_abbr[:], dayticks=True, monthlabels=calendar.month_abbr[1:], monthticks=True, ax=None, **kwargs): """ Plot one year from a timeseries as a calendar heatmap. Parameters ---------- data : Series Data for the plot. Must be indexed by a DatetimeIndex. year : integer Only data indexed by this year will be plotted. If `None`, the first year for which there is data will be plotted. how : string Method for resampling data by day. If `None`, assume data is already sampled by day and don't resample. Otherwise, this is passed to Pandas `Series.resample`. vmin, vmax : floats Values to anchor the colormap. If `None`, min and max are used after resampling data by day. cmap : matplotlib colormap name or object The mapping from data values to color space. fillcolor : matplotlib color Color to use for days without data. linewidth : float Width of the lines that will divide each day. linecolor : color Color of the lines that will divide each day. If `None`, the axes background color is used, or 'white' if it is transparent. daylabels : list Strings to use as labels for days, must be of length 7. dayticks : list or int or bool If `True`, label all days. If `False`, don't label days. If a list, only label days with these indices. If an integer, label every n day. monthlabels : list Strings to use as labels for months, must be of length 12. monthticks : list or int or bool If `True`, label all months. If `False`, don't label months. If a list, only label months with these indices. If an integer, label every n month. ax : matplotlib Axes Axes in which to draw the plot, otherwise use the currently-active Axes. kwargs : other keyword arguments All other keyword arguments are passed to matplotlib `ax.pcolormesh`. Returns ------- ax : matplotlib Axes Axes object with the calendar heatmap. Examples -------- By default, `yearplot` plots the first year and sums the values per day: .. plot:: :context: close-figs calmap.yearplot(events) We can choose which year is plotted with the `year` keyword argment: .. plot:: :context: close-figs calmap.yearplot(events, year=2015) The appearance can be changed by using another colormap. Here we also use a darker fill color for days without data and remove the lines: .. plot:: :context: close-figs calmap.yearplot(events, cmap='YlGn', fillcolor='grey', linewidth=0) The axis tick labels can look a bit crowded. We can ask to draw only every nth label, or explicitely supply the label indices. The labels themselves can also be customized: .. plot:: :context: close-figs calmap.yearplot(events, monthticks=3, daylabels='MTWTFSS', dayticks=[0, 2, 4, 6]) """ if year is None: year = data.index.sort_values()[0].year if how is None: # Assume already sampled by day. by_day = data else: # Sample by day. if _pandas_18: by_day = data.resample('D').agg(how) else: by_day = data.resample('D', how=how) # Min and max per day. if vmin is None: vmin = by_day.min() if vmax is None: vmax = by_day.max() if ax is None: ax = plt.gca() if linecolor is None: # Unfortunately, linecolor cannot be transparent, as it is drawn on # top of the heatmap cells. Therefore it is only possible to mimic # transparent lines by setting them to the axes background color. This # of course won't work when the axes itself has a transparent # background so in that case we default to white which will usually be # the figure or canvas background color. linecolor = ax.get_axis_bgcolor() if ColorConverter().to_rgba(linecolor)[-1] == 0: linecolor = 'white' # Filter on year. by_day = by_day[str(year)] # Add missing days. by_day = by_day.reindex( pd.date_range(start=str(year), end=str(year + 1), freq='D')[:-1]) # Create data frame we can pivot later. by_day = pd.DataFrame({'data': by_day, 'fill': 1, 'day': by_day.index.dayofweek, 'week': by_day.index.week}) # There may be some days assigned to previous year's last week or # next year's first week. We create new week numbers for them so # the ordering stays intact and week/day pairs unique. by_day.loc[(by_day.index.month == 1) & (by_day.week > 50), 'week'] = 0 by_day.loc[(by_day.index.month == 12) & (by_day.week < 10), 'week'] \ = by_day.week.max() + 1 # Pivot data on day and week and mask NaN days. plot_data = by_day.pivot('day', 'week', 'data').values[::-1] plot_data = np.ma.masked_where(np.isnan(plot_data), plot_data) # Do the same for all days of the year, not just those we have data for. fill_data = by_day.pivot('day', 'week', 'fill').values[::-1] fill_data = np.ma.masked_where(np.isnan(fill_data), fill_data) # Draw heatmap for all days of the year with fill color. ax.pcolormesh(fill_data, vmin=0, vmax=1, cmap=ListedColormap([fillcolor])) # Draw heatmap. kwargs['linewidth'] = linewidth kwargs['edgecolors'] = linecolor ax.pcolormesh(plot_data, vmin=vmin, vmax=vmax, cmap=cmap, **kwargs) # Limit heatmap to our data. ax.set(xlim=(0, plot_data.shape[1]), ylim=(0, plot_data.shape[0])) # Square cells. ax.set_aspect('equal') # Remove spines and ticks. for side in ('top', 'right', 'left', 'bottom'): ax.spines[side].set_visible(False) ax.xaxis.set_tick_params(which='both', length=0) ax.yaxis.set_tick_params(which='both', length=0) # Get indices for monthlabels. if monthticks is True: monthticks = range(len(monthlabels)) elif monthticks is False: monthticks = [] elif isinstance(monthticks, int): monthticks = range(len(monthlabels))[monthticks // 2::monthticks] # Get indices for daylabels. if dayticks is True: dayticks = range(len(daylabels)) elif dayticks is False: dayticks = [] elif isinstance(dayticks, int): dayticks = range(len(daylabels))[dayticks // 2::dayticks] ax.set_xlabel('') ax.set_xticks([by_day.ix[datetime.date(year, i + 1, 15)].week for i in monthticks]) ax.set_xticklabels([monthlabels[i] for i in monthticks], ha='center') ax.set_ylabel('') ax.yaxis.set_ticks_position('right') ax.set_yticks([6 - i + 0.5 for i in dayticks]) ax.set_yticklabels([daylabels[i] for i in dayticks], rotation='horizontal', va='center') return ax
def create_linear_segmented_colormap(cmapname, min_val, max_val, transition_vals, transition_colors): ''' Use argument values to fill in the dict used in LinearSegmentedColormap +------------------+-----------+-------------------------------------------------------+ | Parameters: | Type: | Description: | +==================+===========+=======================================================+ | cmapname: | *str* | Name to attach to the matplotlib.color ColorMap object| +------------------+-----------+-------------------------------------------------------+ | min_val: | *float* | Overall minimum value for the colormap | | | | Range must be normalized between 0 and 1 | +------------------+-----------+-------------------------------------------------------+ | max_val: | *float* | Overall maximum value for the colormap | | | | Range must be normalized between 0 and 1 | | | | | +------------------+-----------+-------------------------------------------------------+ | transition_vals: | *list* | A list of value ranges specified as tuples for | | | of | generating a specific range of colors | | |*tuples* | ie [(0, 10), (10, 30), (30, 60)] | +------------------+-----------+-------------------------------------------------------+ |transition_colors:| *list* | A list of color ranges specified as tuples for | | | of | generating a specific range of colors | | |*tuples* | corresponding to the transition_vals specified | | | of | above | | |*colors* | ie [('yellow', 'orange'), | | | | ('pink', 'red'), | | | | ('violet', 'purple')] | +------------------+-----------+-------------------------------------------------------+ TRANSITIONPOINT1 = 0.0 TRANSITIONPOINT4 = 1.0 cmdict = { 'red' : ((TRANSITIONPOINT1, IGNORED, 1to2STARTCOLOR), (TRANSITIONPOINT2, 1to2ENDCOLOR, 2to3STARTCOLOR), (TRANSITIONPOINT3, 2to3ENDCOLOR, 3to4STARTCOLOR), (TRANSITIONPOINT4, 3to4ENDCOLOR, IGNORED)), 'green' : ((TRANSITIONPOINT1, IGNORED, 1to2STARTCOLOR), (TRANSITIONPOINT2, 1to2ENDCOLOR, 2to3STARTCOLOR), (TRANSITIONPOINT3, 2to3ENDCOLOR, 3to4STARTCOLOR), (TRANSITIONPOINT4, 3to4ENDCOLOR, IGNORED)), 'blue' : ((TRANSITIONPOINT1, IGNORED, 1to2STARTCOLOR), (TRANSITIONPOINT2, 1to2ENDCOLOR, 2to3STARTCOLOR), (TRANSITIONPOINT3, 2to3ENDCOLOR, 3to4STARTCOLOR), (TRANSITIONPOINT4, 3to4ENDCOLOR, IGNORED)), } ''' from matplotlib.colors import ColorConverter, LinearSegmentedColormap # Sort transitions on start_val bluetuple = () greentuple = () redtuple = () start_color = None end_color = None old_end_color = [0, 0, 0] for transition_val, transition_color in zip(transition_vals, transition_colors): start_val = transition_val[0] end_val = transition_val[1] tstart_color = transition_color[0] tend_color = transition_color[1] # Must start with 0.0 ! transition_point = (start_val - min_val) / float((max_val - min_val)) cc = ColorConverter() # Convert start/end color to string, tuple, whatever matplotlib can use. try: start_color = cc.to_rgb(str(tstart_color)) except ValueError: # Allow for tuples as well as string representations start_color = cc.to_rgb(eval(str(tstart_color))) try: end_color = cc.to_rgb(str(tend_color)) except ValueError: end_color = cc.to_rgb(eval(str(tend_color))) bluetuple += ((transition_point, old_end_color[2], start_color[2]), ) redtuple += ((transition_point, old_end_color[0], start_color[0]), ) greentuple += ((transition_point, old_end_color[1], start_color[1]), ) LOG.info(' Transition point: ' + str(transition_point) + ': ' + str(start_val) + ' to ' + str(end_val)) LOG.info(' Start color: %-10s %-40s', str(tstart_color), str(start_color)) LOG.info(' End color: %-10s %-40s', str(tend_color), str(end_color)) old_end_color = end_color # Must finish with 1.0 ! transition_point = (end_val - min_val) / float((max_val - min_val)) bluetuple += ((transition_point, old_end_color[2], start_color[2]), ) redtuple += ((transition_point, old_end_color[0], start_color[0]), ) greentuple += ((transition_point, old_end_color[1], start_color[1]), ) cmdict = {'red': redtuple, 'green': greentuple, 'blue': bluetuple} cm = LinearSegmentedColormap(cmapname, cmdict) return cm
def scale_lightness(c, factor): # idea from https://stackoverflow.com/a/60562502 rgb = ColorConverter.to_rgb(c) h, l, s = colorsys.rgb_to_hls(*rgb) # manipulate h, l, s values and return as rgb return colorsys.hls_to_rgb(h, min(1, l * factor), s)
def wigner_cmap(W, levels=1024, shift=0, max_color='#09224F', mid_color='#FFFFFF', min_color='#530017', neg_color='#FF97D4', invert=False): """A custom colormap that emphasizes negative values by creating a nonlinear colormap. Parameters ---------- W : array Wigner function array, or any array. levels : int Number of color levels to create. shift : float Shifts the value at which Wigner elements are emphasized. This parameter should typically be negative and small (i.e -1e-5). max_color : str String for color corresponding to maximum value of data. Accepts any string format compatible with the Matplotlib.colors.ColorConverter. mid_color : str Color corresponding to zero values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter. min_color : str Color corresponding to minimum data values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter. neg_color : str Color that starts highlighting negative values. Accepts any string format compatible with the Matplotlib.colors.ColorConverter. invert : bool Invert the color scheme for negative values so that smaller negative values have darker color. Returns ------- Returns a Matplotlib colormap instance for use in plotting. Notes ----- The 'shift' parameter allows you to vary where the colormap begins to highlight negative colors. This is beneficial in cases where there are small negative Wigner elements due to numerical round-off and/or truncation. """ cc = ColorConverter() max_color = np.array(cc.to_rgba(max_color), dtype=float) mid_color = np.array(cc.to_rgba(mid_color), dtype=float) if invert: min_color = np.array(cc.to_rgba(neg_color), dtype=float) neg_color = np.array(cc.to_rgba(min_color), dtype=float) else: min_color = np.array(cc.to_rgba(min_color), dtype=float) neg_color = np.array(cc.to_rgba(neg_color), dtype=float) # get min and max values from Wigner function bounds = [W.min(), W.max()] # create empty array for RGBA colors adjust_RGBA = np.hstack((np.zeros((levels, 3)), np.ones((levels, 1)))) zero_pos = np.round(levels * np.abs(shift - bounds[0]) / (bounds[1] - bounds[0])) num_pos = levels - zero_pos num_neg = zero_pos - 1 # set zero values to mid_color adjust_RGBA[zero_pos] = mid_color # interpolate colors for k in range(0, levels): if k < zero_pos: interp = k / (num_neg + 1.0) adjust_RGBA[k][0:3] = (1.0 - interp) * \ min_color[0:3] + interp * neg_color[0:3] elif k > zero_pos: interp = (k - zero_pos) / (num_pos + 1.0) adjust_RGBA[k][0:3] = (1.0 - interp) * \ mid_color[0:3] + interp * max_color[0:3] # create colormap wig_cmap = mpl.colors.LinearSegmentedColormap.from_list('wigner_cmap', adjust_RGBA, N=levels) return wig_cmap
def plot_results(parameters, samples_green=[], samples_red=[], samples_blue=[], samples_black=[], poly_green=[], poly_red=[], poly_blue_crossed=[], poly_blue_dotted=[], poly_blue=[], poly_black=[], anchor_points=[], additional_arrows=[], path_to_pdf=None, path_to_src=None, display=False): """ Plot all results. :param parameters: Parameters. :param samples_green: Samples with color green. :param samples_red: Samples with color red. :param samples_blue: Samples with color blue. :param poly_green: Polygons with color green. :param poly_red: Polygons with color red. :param poly_blue_crossed: Polygons with color blue and crossed hatch. :param poly_blue_dotted: Polygons with color blue and dotted hatch. :param poly_blue: Polygons with color blue. :param anchor_points: List of anchor points with direction. :param additional_arrows: List of additional arrows. :param path_to_pdf: Paths for pdf file or None if no file should be generated. :param path_to_src: Paths for the pgf source files or None if no file should be generated. :param display: If true, the plot will be displayed automatically. """ logger.info("Plot results") if len(parameters) > 2: raise ValueError("Cannot plot for more than 2 parameters.") pgf_with_rc_fonts = { "font.family": "serif", "font.serif": [] # use latex default serif font #"font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font } pyplot.rcParams.update(pgf_with_rc_fonts) if Plot.flip_green_red: samples_green, samples_red = samples_red, samples_green poly_green, poly_red = poly_red, poly_green if len(parameters) == 1: fig = pyplot.figure() ax1 = fig.add_subplot(111) ax1.plot(samples_green, len(samples_green) * [1], "o", c='green') ax1.plot(samples_red, len(samples_red) * [1], "x", c='red') ax1.plot(samples_blue, len(samples_blue) * [1], ".", c='blue') ax1.plot(samples_black, len(samples_black) * [1], "+", c='black') ax1.axes.get_yaxis().set_visible(False) ax1.set_xlabel(str(parameters[0].name)) ax1.patch.set_visible(False) fig.patch.set_visible(False) # get rid of the frame for spine in fig.gca().spines.values(): spine.set_visible(False) if path_to_pdf is not None: pyplot.savefig(path_to_pdf, format="PDF") print("saved fig: {}".format(path_to_pdf)) if path_to_src is not None: pyplot.savefig(path_to_src, format="PGF") if display: pyplot.show() pyplot.close(fig) elif len(parameters) == 2: fig = pyplot.figure() ax1 = fig.add_subplot(111) for anchor in anchor_points: d = 0.02 dx = d if anchor.dir.value[0] else -d dy = d if anchor.dir.value[1] else -d ax1.arrow(anchor.pos.x, anchor.pos.y, dx, dy, head_width=d / 2, head_length=d / 2, color='blue') colorc = ColorConverter() for line in additional_arrows: line_points = list(line.coords) point1 = line_points[0] point2 = line_points[1] ax1.arrow(point1[0], point1[1], point2[0] - point1[0], point2[1] - point1[1], head_width=0.01, head_length=0.01, color='gray') for box in poly_green: Plot.plot_poly(ax1, box, fc=colorc.to_rgba("#4aa02c", 0.6), ec=colorc.to_rgba("#4aa02c"), hatch="o") for box in poly_red: Plot.plot_poly(ax1, box, fc=colorc.to_rgba("#c11b17", 0.6), ec=colorc.to_rgba("#c11b17"), hatch="x") for box in poly_blue: Plot.plot_poly(ax1, box, fc=colorc.to_rgba("#1b17c1", 0.6), ec=colorc.to_rgba("#1b17c1")) for box in poly_black: Plot.plot_poly(ax1, box, fc=colorc.to_rgba("#030303", 0.6), ec=colorc.to_rgba("#030303"), hatch="+") for box in poly_blue_crossed: Plot.plot_poly(ax1, box, fc=colorc.to_rgba("#1b17c1", 0.6), ec=colorc.to_rgba("#1b17c1"), hatch="x") for box in poly_blue_dotted: Plot.plot_poly(ax1, box, fc=colorc.to_rgba("#1b17c1", 0.6), ec=colorc.to_rgba("#1b17c1"), hatch="o") # Draw the samples last x_coords = [x for x, y in samples_green] y_coords = [y for x, y in samples_green] ax1.scatter(x_coords, y_coords, marker='o', c='green') x_coords = [x for x, y in samples_red] y_coords = [y for x, y in samples_red] ax1.scatter(x_coords, y_coords, marker='x', c='red') x_coords = [x for x, y in samples_blue] y_coords = [y for x, y in samples_blue] ax1.scatter(x_coords, y_coords, marker='.', c='blue') x_coords = [x for x, y in samples_black] y_coords = [y for x, y in samples_black] ax1.scatter(x_coords, y_coords, marker='+', c='black') ax1.set_xlim([ float(parameters[0].interval.left_bound()), float(parameters[0].interval.right_bound()) ]) ax1.set_ylim([ float(parameters[1].interval.left_bound()), float(parameters[1].interval.right_bound()) ]) ax1.set_xlabel(str(parameters[0].name)) ax1.set_ylabel(str(parameters[1].name)) if path_to_pdf is not None: pyplot.savefig(path_to_pdf, format="PDF") if path_to_src is not None: pyplot.savefig(path_to_src, format="PGF") if display: pyplot.show() pyplot.close(fig)
def color2rgb(color): from matplotlib.colors import ColorConverter result = ColorConverter().to_rgb(color) return result
def _update_cmap_from_color(self): cmap = get_translucent_cmap(*ColorConverter().to_rgb(self.state.color)) self._multivol.set_cmap(self.id, cmap) self.redraw()
import platform from collections import OrderedDict import numpy as np from matplotlib.colors import ColorConverter from qtpy import QtWidgets from glue.core.message import SettingsChangeMessage from glue.utils.qt import load_ui, ColorProperty, get_qapp from glue.utils.qt.widget_properties import (CurrentComboTextProperty, ValueProperty, ButtonProperty) from glue._settings_helpers import save_settings __all__ = ["PreferencesDialog"] rgb = ColorConverter().to_rgb AUTOLINK_OPTIONS = OrderedDict([('always_show', 'Always show suggestions'), ('always_accept', 'Always accept suggestions'), ('always_ignore', 'Always ignore suggestions') ]) class AutolinkPreferencesPane(QtWidgets.QWidget): def __init__(self, parent=None): super(AutolinkPreferencesPane, self).__init__(parent=parent) from glue.config import settings, autolinker # noqa layout = QtWidgets.QGridLayout()
def process_block(self, block_text, user, block_id, **params): def int_or_none(val): """Returns an integer or none. May pass anything """ try: ret = int(val) except ValueError: ret = None return ret def int_or_default(val, default=0): """ Returns int or a given default """ try: ret = int(val) except ValueError: ret = default return ret def float_or_default(val, default=0.0): """ Returns float or a given default """ try: ret = float(val) except ValueError: ret = default return ret tokens = self.parse_block(block_text) # get our tokens db_name = tokens.get(self.ATTR_DB, settings.DATABASE_DEFAULT_ALIAS).strip() # chart title. empty by default chart_title = tokens.get(self.ATTR_TITLE, '').strip() # chart width and height in pixels. Beware, the user # inevitably will write anything but valid numbers chart_width = int_or_none(tokens.get(self.ATTR_WIDTH, '').strip()) chart_height = int_or_none(tokens.get(self.ATTR_HEIGHT, '').strip()) ylabel = tokens.get(self.ATTR_YLABEL, '').strip() xlabel = tokens.get(self.ATTR_XLABEL, '').strip() font_size = int_or_default( tokens.get(self.ATTR_FONT_SIZE, self.DEFAULT_FONT_SIZE)) if font_size <= 1: font_size = self.DEFAULT_FONT_SIZE if font_size >= 100: font_size = self.DEFAULT_FONT_SIZE # grid grid = tokens.get(self.ATTR_GRID, 'none').strip().lower() if grid not in ('x', 'y', 'both', 'none'): grid = 'none' # also check for negative numbers or zeroes if (chart_width is not None) and (chart_height is not None): if (chart_width <= 0) or (chart_height <= 0): # both none chart_width = None chart_height = None else: # some of them are none # set both to none chart_width = None chart_height = None # xtick rotation x_tick_rotation = int_or_default( tokens.get(self.ATTR_XTICK_ROTATION, self.DEFAULT_XTICK_ROTATION)) if x_tick_rotation > 90: x_tick_rotation = 90 if x_tick_rotation < -90: x_tick_rotation = -90 # legend legend_str = tokens.get(self.ATTR_LEGEND, self.ATTR_VALUE_NO).strip().lower() if legend_str not in (self.ATTR_VALUE_NO, self.ATTR_VALUE_YES): legend_str = self.ATTR_VALUE_NO # legend location legend_location = tokens.get( self.ATTR_LEGEND_LOCATION, self.DEFAULT_LEGEND_LOCATION).strip().lower() # this is not necessary, matplotlib does it by himself, # yet we check it here to avoid warnings on stdout if legend_location not in self.VALID_LEGEND_LOCATIONS: legend_location = self.DEFAULT_LEGEND_LOCATION # bar width bar_width = float_or_default( tokens.get(self.ATTR_BAR_WIDTH, self.DEFAULT_BAR_WIDTH), self.DEFAULT_BAR_WIDTH) if bar_width > self.MAX_BAR_WIDTH: bar_width = self.MAX_BAR_WIDTH if bar_width < self.MIN_BAR_WIDTH: bar_width = self.MIN_BAR_WIDTH # stacked stacked = tokens.get(self.ATTR_STACKED, self.ATTR_VALUE_NO).strip().lower() if stacked not in (self.ATTR_VALUE_YES, self.ATTR_VALUE_NO): stacked = self.ATTR_VALUE_NO con = None # if anything, we rethrow the exception try: db = settings.DATABASES.get(db_name, None) # non-existent database - exception if db == None: raise DwException(db_name, "Unknown database %s." % db_name) true_sql = tokens.sqltext # now that we have a sql, try to replace parameters in it. # Parameter looks like ${param_name} p = re.compile(u'\$\{[a-z]+[0-9]*\}') # get the list of all mentioned params lst = p.findall(true_sql) # loop through all these variables and try to replace # them with params passed to us for item in lst: stripped_item = item[2:-1] # TODO check for default value here value = 'None' if stripped_item in params: value = params[stripped_item] value = urllib.unquote(value) # replace it true_sql = true_sql.replace(item, value) # get a connection from somewhere con = self.get_con(db) cur = con.cursor() cur.execute(true_sql) row = cur.fetchone() # TODO Now if row is None it means the set is empty # in this case we have to generate a stub # for now assume the data is present # Get columns for labels # We need at least two columns # first one is x axis, column heading does not matter # the second is y axis values # the third one is the color of values # if there is no third column, use default color # which is gray columns = cur.description col_count = len(columns) if col_count < 2: raise DwException(db_name, "There should be at least two columns") # second column should be a number. Don't test it here. # we will try to test each value # every odd column is value # every even column is color # Now traverse all the rows # x_tick_marks is col 0 values x_tick_marks = list() # y_values is an array of bar heights # stored in the second column, fourth etc. columns # this is array of arrays y_values_array = list() y_colors_array = list() for i in range(1, col_count): is_value = i % 2 == 1 is_color = i % 2 == 0 if is_value is True: y_values = list() y_values_array.append(y_values) # add color array in any case y_colors = list() y_colors_array.append(y_colors) #if is_color is True: #y_colors_array.append(y_colors) #y_values = list() # bar_colors is an array of bar colors # stored in the third column # if there is no third column, # assume the color is grey #y_colors = list() # Now traverse. If row count is too big, # just stop where it exceeds the maximum allowed number # which we set to 100 for now curr_bar = 0 color_converter = ColorConverter() while row is not None: # tick mark as unicode mark = row[0] if mark is None: mark = '' if type(mark) is str: mark = mark.decode('utf-8') elif type(mark) is unicode: pass else: # TODO maybe a number # we need to convert it to a string # according to it's type (integer, decimal, float) # date, time, datetime mark = unicode(mark) x_tick_marks.append(mark) # collect values and colors for i in range(1, col_count): is_value = i % 2 == 1 is_color = i % 2 == 0 # value itself. plot does not support Decimal, # need to convert to float if is_value is True: value_index = i / 2 y_values = y_values_array[value_index] value = row[i] tp = type(value).__name__ if tp is 'Decimal': value = float(value) # all nulls are replaced with zeroes if value is None: value = 0.0 y_values.append(value) # now colors color_col = i + 1 y_colors = y_colors_array[value_index] # color himself +1 col if exists color_str = None if color_col < len(row): color_str = self.make_unicode_or_none(row[i + 1]) if color_str is None: color_str = self.DEFAULT_BAR_COLOR # Now try to make a color. If it's unsuccessful, # it returns an exception try: color_rgba = color_converter.to_rgba(color_str) except Exception, e: #sys.stderr.write("Color error: %s\n" % color_str) color_rgba = color_converter.to_rgba( self.USER_ERROR_BAR_COLOR) # Hopefully, color_rgba is now set # to a tuple of R, G, B and Alpha y_colors.append(color_rgba) # increment row counter curr_bar += 1 if curr_bar >= self.MAX_BARS: break else: row = cur.fetchone() # Now we have collected all the values, marks and colors con.close() con = None # Build a graph # 80 dots per inch. So 7 x 4 inches will make 560 x 320 pixels if (chart_width > 0) and (chart_height > 0): fig = plt.figure(figsize=[chart_width / 80, chart_height / 80], dpi=80) else: fig = plt.figure() ax = fig.add_subplot(111) # data size #N = len(curr_bar) # number of bar groups - scale units for x axis = number of query rows # arrange N between 0 and N-1. Returns an array ind = np.arange(curr_bar) # distribute equally # todo expose bar width if stacked == self.ATTR_VALUE_NO: width = bar_width / len( y_values_array) # width of the bars (measures?) else: width = bar_width min_value = 0 max_value = 0 for y_values in y_values_array: # remember it may be negative temp_min_value = min(y_values) min_value = min(temp_min_value, min_value) if min_value > 0: min_value = 0 temp_max_value = max(y_values) max_value = max(temp_max_value, max_value) if max_value < 0: max_value = 0 # now add additional 10% of min-max range at the top value_range = max_value - min_value top_y_axis_margin = value_range * self.DEFAULT_TOP_Y_AXIS_MARGIN # no margin for bottom bottom_y_axis_margin = 0 # if we have negative bars, set margin below too if min_value < 0: bottom_y_axis_margin = top_y_axis_margin # here we set final max and min y axis values to account for our margins max_y_axis_value = max_value + top_y_axis_margin min_y_axis_value = min_value - bottom_y_axis_margin # cycle through values and draw bars for i in range(len(y_values_array)): y_values = y_values_array[i] y_colors = y_colors_array[i] # bar labels # get a description # it's in columns 1,3,5 etc. # i=0 => col=1 # i=1 => col=3 col_index = i * 2 + 1 col = columns[col_index] bar_label = col[0] if type(col[0]) is str: bar_label = col[0].decode('utf-8') elif type(col[0]) is unicode: bar_label = col[0] # The Drawing if stacked == self.ATTR_VALUE_NO: rects1 = ax.bar(ind + i * width, y_values, width, color=y_colors, label=bar_label) else: rects1 = ax.bar(ind, y_values, width, color=y_colors, label=bar_label) ax.set_xlim(-1 + bar_width, len(ind)) ax.set_ylim(min_y_axis_value, max_y_axis_value) # draw horizontal grid lines if grid <> 'none': ax.grid(which='major', axis=grid) if ylabel <> '': plt.ylabel(ylabel, fontsize=font_size) if xlabel <> '': plt.xlabel(xlabel, fontsize=font_size) ax.set_title(chart_title, fontsize=font_size) # font for y major ticks for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(font_size) # ticks on top and bottom ax.set_xticks(ind + bar_width / 2) #canvas = FigureCanvasAgg(fig) x_tick_labels = ax.set_xticklabels(x_tick_marks) plt.setp(x_tick_labels, rotation=x_tick_rotation, fontsize=font_size) # legend if legend_str == self.ATTR_VALUE_YES: ax.legend(loc=legend_location, prop={'size': font_size}) plt.tight_layout() tempfiledir = cherrypy.config['dwwiki.tempfiledir'] tempfile.tempdir = tempfiledir try: f = tempfile.NamedTemporaryFile(delete=False) # print graph to a temporary file # TODO we assume it prints png. Yet I don't know # why. Is it the default format? #canvas.print_figure(f) #canvas.print_png(f) fig.savefig(f) f.close() # Now all we need is to encode the file in base64, # then serve it as an <img> input_file = open(f.name, 'rb') output_file = cStringIO.StringIO() base64.encode(input_file, output_file) # we have it as a png string #yield '<img alt="graph" src="data:image/png;base64,' yield '<img alt="graph" src="data:image/png;base64,' yield output_file.getvalue() yield "\"/>\n" output_file.close() input_file.close() finally: os.remove(f.name)
def plotBoundary(classifier, dataset='iris', split=0.7, fname=None): X, y, pcadim = fetchDataset(dataset) xTr, yTr, xTe, yTe, trIdx, teIdx = trteSplitEven(X, y, split, 1) classes = np.unique(y) 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)) # Train trained_classifier = classifier.trainClassifier(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): # Predict grid[yi, xi] = trained_classifier.classify(np.array([[xx, yy]])) ys = [i + xx + (i * xx)**2 for i in range(len(classes))] colormap = cm.rainbow(np.linspace(0, 1, len(ys))) fig = plt.figure() # 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 trClIdx = np.where(y[trIdx] == c)[0] teClIdx = np.where(y[teIdx] == c)[0] plt.scatter(xTr[trClIdx, 0], xTr[trClIdx, 1], marker='o', c=color, s=40, alpha=0.5, label="Class " + str(c) + " Train") plt.scatter(xTe[teClIdx, 0], xTe[teClIdx, 1], marker='*', c=color, s=50, alpha=0.8, label="Class " + str(c) + " Test") plt.legend(bbox_to_anchor=(1., 1), loc=2, borderaxespad=0.) fig.subplots_adjust(right=0.7) if fname: plt.savefig(fname) else: plt.show()
# This artist can be used to deal with the sampling of the data as well as any # RGB blending. from __future__ import absolute_import import numpy as np from matplotlib.colors import ColorConverter, Colormap from astropy.visualization import (LinearStretch, SqrtStretch, AsinhStretch, LogStretch, ManualInterval, ContrastBiasStretch) __all__ = ['CompositeArray'] COLOR_CONVERTER = ColorConverter() STRETCHES = { 'linear': LinearStretch, 'sqrt': SqrtStretch, 'arcsinh': AsinhStretch, 'log': LogStretch } class CompositeArray(object): def __init__(self, **kwargs): # We keep a dictionary of layers. The key should be the UUID of the # layer artist, and the values should be dictionaries that contain # 'zorder', 'visible', 'array', 'color', and 'alpha'. self.layers = {}
def yearplot(data, year=None, how='sum', vmin=None, vmax=None, cmap='viridis', fillcolor='whitesmoke', linewidth=1, linecolor=None, edgecolor='gray', daylabels=calendar.day_abbr[:], dayticks=True, dropzero=None, textformat=None, textfiller='', textcolor='black', monthlabels=calendar.month_abbr[1:], monthlabeloffset=15, monthticks=True, ax=None, **kwargs): """ Plot one year from a timeseries as a calendar heatmap. Parameters ---------- data : Series Data for the plot. Must be indexed by a DatetimeIndex. year : integer Only data indexed by this year will be plotted. If `None`, the first year for which there is data will be plotted. how : string Method for resampling data by day. If `None`, assume data is already sampled by day and don't resample. Otherwise, this is passed to Pandas `Series.resample`. vmin, vmax : floats Values to anchor the colormap. If `None`, min and max are used after resampling data by day. cmap : matplotlib colormap name or object The mapping from data values to color space. fillcolor : matplotlib color Color to use for days without data. linewidth : float Width of the lines that will divide each day. linecolor : color Color of the lines that will divide each day. If `None`, the axes background color is used, or 'white' if it is transparent. daylabels : list Strings to use as labels for days, must be of length 7. dayticks : list or int or bool If `True`, label all days. If `False`, don't label days. If a list, only label days with these indices. If an integer, label every n day. dropzero : bool If `True`, don't fill a color for days with a zero value. monthlabels : list Strings to use as labels for months, must be of length 12. monthlabeloffset : integer Day offset for labels for months to adjust horizontal alignment. monthticks : list or int or bool If `True`, label all months. If `False`, don't label months. If a list, only label months with these indices. If an integer, label every n month. edgecolor : color Color of the lines that will divide months. textformat : string Text format string for grid cell text textfiller : string Fallback text for grid cell text for cells with no data textcolor : color Color of the grid cell text ax : matplotlib Axes Axes in which to draw the plot, otherwise use the currently-active Axes. kwargs : other keyword arguments All other keyword arguments are passed to matplotlib `ax.pcolormesh`. Returns ------- ax : matplotlib Axes Axes object with the calendar heatmap. """ if year is None: year = data.index.sort_values()[0].year if how is None: # Assume already sampled by day. by_day = data else: # Sample by day. by_day = data.resample('D').agg(how) # Default to dropping zero values for a series with over 50% of rows being zero. if by_day[by_day == 0].count() > 0.5 * by_day.count(): dropzero = True if dropzero: by_day = by_day.replace({0: np.nan}).dropna() # Min and max per day. if vmin is None: vmin = by_day.min() if vmax is None: vmax = by_day.max() if ax is None: ax = plt.gca() if linecolor is None: # Unfortunately, linecolor cannot be transparent, as it is drawn on # top of the heatmap cells. Therefore it is only possible to mimic # transparent lines by setting them to the axes background color. This # of course won't work when the axes itself has a transparent # background so in that case we default to white which will usually be # the figure or canvas background color. linecolor = ax.get_facecolor() if ColorConverter().to_rgba(linecolor)[-1] == 0: linecolor = 'white' # Filter on year. by_day = by_day[str(year)] # Add missing days. by_day = by_day.reindex( pd.date_range(start=str(year), end=str(year + 1), freq='D', tz=by_day.index.tzinfo)[:-1]) # Create data frame we can pivot later. by_day = pd.DataFrame({'data': by_day, 'fill': 1, 'day': by_day.index.dayofweek, 'week': by_day.index.isocalendar().week}) # There may be some days assigned to previous year's last week or # next year's first week. We create new week numbers for them so # the ordering stays intact and week/day pairs unique. by_day.loc[(by_day.index.month == 1) & (by_day.week > 50), 'week'] = 0 by_day.loc[(by_day.index.month == 12) & (by_day.week < 10), 'week'] \ = by_day.week.max() + 1 # Pivot data on day and week and mask NaN days. plot_data = by_day.pivot('day', 'week', 'data').values[::-1] plot_data = np.ma.masked_where(np.isnan(plot_data), plot_data) # Do the same for all days of the year, not just those we have data for. fill_data = by_day.pivot('day', 'week', 'fill').values[::-1] fill_data = np.ma.masked_where(np.isnan(fill_data), fill_data) # Draw heatmap for all days of the year with fill color. ax.pcolormesh(fill_data, vmin=0, vmax=1, cmap=ListedColormap([fillcolor])) # Draw heatmap. kwargs['linewidth'] = linewidth kwargs['edgecolors'] = linecolor ax.pcolormesh(plot_data, vmin=vmin, vmax=vmax, cmap=cmap, **kwargs) # Limit heatmap to our data. ax.set(xlim=(0, plot_data.shape[1]), ylim=(0, plot_data.shape[0])) # Square cells. ax.set_aspect('equal') # Remove spines and ticks. for side in ('top', 'right', 'left', 'bottom'): ax.spines[side].set_visible(False) for axis in (ax.xaxis, ax.yaxis): axis.set_tick_params(which='both', length=0) # Get indices for monthlabels. if monthticks is True: monthticks = range(len(monthlabels)) elif monthticks is False: monthticks = [] # Get indices for daylabels. if dayticks is True: dayticks = range(len(daylabels)) elif dayticks is False: dayticks = [] ax.set_xlabel('') ax.set_xticks([by_day.loc[pd.Timestamp( datetime.date(year, i + 1, monthlabeloffset))].week for i in monthticks]) ax.set_xticklabels([monthlabels[i] for i in monthticks]) ax.set_ylabel('') ax.yaxis.set_ticks_position('right') ax.set_yticks([6 - i + 0.5 for i in dayticks]) ax.set_yticklabels([daylabels[i] for i in dayticks], rotation='horizontal', va='center') # Text in mesh grid if format is specified. if textformat is not None: for y in range(plot_data.shape[0]): for x in range(plot_data.shape[1]): content = '' masked = plot_data[y, x] if masked is np.ma.masked: if fill_data[y, x] == 1: content = textfiller else: content = textformat.format(masked) ax.text(x + 0.5, y + 0.5, content, color=textcolor, ha='center', va='center') # Month borders code credited to https://github.com/rougier/calendar-heatmap xticks = [] start = datetime.datetime(year, 1, 1).weekday() for month in range(1, 13): first = datetime.datetime(year, month, 1) last = first + relativedelta(months=1, days=-1) y0 = 7 - first.weekday() y1 = 7 - last.weekday() x0 = (int(first.strftime('%j'))+start-1)//7 x1 = (int(last.strftime('%j'))+start-1)//7 P = [(x0, y0), (x0+1, y0), (x0+1, 7), (x1+1, 7), (x1+1, y1-1), (x1, y1-1), (x1, 0), (x0, 0) ] xticks.append(x0 + (x1-x0+1)/2) poly = Polygon(P, edgecolor=edgecolor, facecolor='None', linewidth=linewidth, zorder=20, clip_on=False) ax.add_artist(poly) return ax
def to_rgb(image, colors=None, normed=True): """This converts a greyscale or multichannel image to an RGB image, with given channel colors. Parameters ---------- image : ndarray Multichannel image (channel dimension is first dimension). When first dimension is longer than 4, the file is interpreted as a greyscale. colors : list of matplotlib.colors List of either single letters, or rgb(a) as lists of floats. The sum of these lists should equal (1.0, 1.0, 1.0), when clipping needs to be avoided. normed : bool, optional Multichannel images will be downsampled to 8-bit RGB, if normed is True. Greyscale images will always give 8-bit RGB. Returns ------- ndarray RGB image, with inner dimension of length 3. The RGB image is clipped so that values lay between 0 and 255. When normed = True (default), datatype is np.uint8, else it is float. """ # identify whether the image has a (leading) channel axis if colors is None: has_channel_axis = image.ndim > 2 and image.shape[0] < 5 else: has_channel_axis = len(colors) == image.shape[0] # identify number of channels and resulting shape if has_channel_axis: channels = image.shape[0] shape_rgb = image.shape[1:] + (3,) else: channels = 1 shape_rgb = image.shape + (3,) if colors is None: # pick colors with high RGB luminance if channels == 1: # white rgbs = [[255, 255, 255]] elif channels == 2: # green, magenta rgbs = [[0, 255, 0], [255, 0, 255]] elif channels == 3: # cyan, green, magenta rgbs = [[0, 255, 255], [0, 255, 0], [255, 0, 255]] elif channels == 4: # cyan, green, magenta, red rgbs = [[0, 255, 255], [0, 255, 0], [255, 0, 255], [255, 0, 0]] else: raise IndexError('Not enough color values to build rgb image') else: # identify rgb values of channels using matplotlib ColorConverter if ColorConverter is None: raise ImportError('Matplotlib required for conversion to rgb') if channels > len(colors): raise IndexError('Not enough color values to build rgb image') rgbs = (ColorConverter().to_rgba_array(colors)*255).astype('uint8') rgbs = rgbs[:channels, :3] if has_channel_axis: result = np.zeros(shape_rgb) for i in range(channels): result += _monochannel_to_rgb(image[i], rgbs[i]) else: result = _monochannel_to_rgb(image, rgbs[0]) result = result.clip(0, 255) if normed: result = (normalize(result) * 255).astype('uint8') return result
def test_hist_plot_1d(): fig, ax = plt.subplots() np.random.seed(0) data = np.random.randn(1000) for p in ['', 'astropyhist']: try: # Check heights for histtype 'bar' bars = hist_plot_1d(ax, data, histtype='bar', plotter=p) assert(np.all([isinstance(b, Patch) for b in bars])) assert(max([b.get_height() for b in bars]) == 1.) assert(np.all(np.array([b.get_height() for b in bars]) <= 1.)) # Check heights for histtype 'step' polygon, = hist_plot_1d(ax, data, histtype='step', plotter=p) assert(isinstance(polygon, Polygon)) trans = polygon.get_transform() - ax.transData assert(np.isclose(trans.transform(polygon.xy)[:, -1].max(), 1., rtol=1e-10, atol=1e-10)) assert(np.all(trans.transform(polygon.xy)[:, -1] <= 1.)) # Check heights for histtype 'stepfilled' polygon, = hist_plot_1d(ax, data, histtype='stepfilled', plotter=p) assert(isinstance(polygon, Polygon)) trans = polygon.get_transform() - ax.transData assert(np.isclose(trans.transform(polygon.xy)[:, -1].max(), 1., rtol=1e-10, atol=1e-10)) assert(np.all(trans.transform(polygon.xy)[:, -1] <= 1.)) # Check arguments are passed onward to underlying function bars = hist_plot_1d(ax, data, histtype='bar', color='r', alpha=0.5, plotter=p) cc = ColorConverter.to_rgba('r', alpha=0.5) assert(np.all([b.get_fc() == cc for b in bars])) bars = hist_plot_1d(ax, data, histtype='bar', cmap=plt.cm.viridis, alpha=0.5, plotter=p) cc = ColorConverter.to_rgba(plt.cm.viridis(0.68), alpha=0.5) assert(np.all([b.get_fc() == cc for b in bars])) polygon, = hist_plot_1d(ax, data, histtype='step', color='r', alpha=0.5, plotter=p) assert(polygon.get_ec() == ColorConverter.to_rgba('r', alpha=0.5)) polygon, = hist_plot_1d(ax, data, histtype='step', cmap=plt.cm.viridis, color='r', plotter=p) assert(polygon.get_ec() == ColorConverter.to_rgba('r')) # Check xmin for xmin in [-np.inf, -0.5]: bars = hist_plot_1d(ax, data, histtype='bar', xmin=xmin, plotter=p) assert((np.array([b.xy[0] for b in bars]) >= xmin).all()) polygon, = hist_plot_1d(ax, data, histtype='step', xmin=xmin) assert((polygon.xy[:, 0] >= xmin).all()) # Check xmax for xmax in [np.inf, 0.5]: bars = hist_plot_1d(ax, data, histtype='bar', xmax=xmax, plotter=p) assert((np.array([b.xy[-1] for b in bars]) <= xmax).all()) polygon, = hist_plot_1d(ax, data, histtype='step', xmax=xmax, plotter=p) assert((polygon.xy[:, 0] <= xmax).all()) # Check xmin and xmax bars = hist_plot_1d(ax, data, histtype='bar', xmin=xmin, xmax=xmax, plotter=p) assert((np.array([b.xy[0] for b in bars]) >= -0.5).all()) assert((np.array([b.xy[-1] for b in bars]) <= 0.5).all()) polygon, = hist_plot_1d(ax, data, histtype='step', xmin=xmin, xmax=xmax, plotter=p) assert((polygon.xy[:, 0] >= -0.5).all()) assert((polygon.xy[:, 0] <= 0.5).all()) plt.close("all") except ImportError: if p == 'astropyhist' and 'astropy' not in sys.modules: pass
def plot_sparse_source_estimates(src, stcs, colors=None, linewidth=2, fontsize=18, bgcolor=(.05, 0, .1), opacity=0.2, brain_color=(0.7, ) * 3, show=True, high_resolution=False, fig_name=None, fig_number=None, labels=None, modes=['cone', 'sphere'], scale_factors=[1, 0.6], verbose=None, **kwargs): """Plot source estimates obtained with sparse solver Active dipoles are represented in a "Glass" brain. If the same source is active in multiple source estimates it is displayed with a sphere otherwise with a cone in 3D. Parameters ---------- src: dict The source space stcs: instance of SourceEstimate or list of instances of SourceEstimate The source estimates (up to 3) colors: list List of colors linewidth: int Line width in 2D plot fontsize: int Font size bgcolor: tuple of length 3 Background color in 3D opacity: float in [0, 1] Opacity of brain mesh brain_color: tuple of length 3 Brain color show: bool Show figures if True fig_name: Mayavi figure name fig_number: Pylab figure number labels: ndarray or list of ndarrays Labels to show sources in clusters. Sources with the same label and the waveforms within each cluster are presented in the same color. labels should be a list of ndarrays when stcs is a list ie. one label for each stc. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). kwargs: kwargs Keyword arguments to pass to mlab.triangular_mesh """ if not isinstance(stcs, list): stcs = [stcs] if labels is not None and not isinstance(labels, list): labels = [labels] if colors is None: colors = COLORS linestyles = ['-', '--', ':'] # Show 3D lh_points = src[0]['rr'] rh_points = src[1]['rr'] points = np.r_[lh_points, rh_points] lh_normals = src[0]['nn'] rh_normals = src[1]['nn'] normals = np.r_[lh_normals, rh_normals] if high_resolution: use_lh_faces = src[0]['tris'] use_rh_faces = src[1]['tris'] else: use_lh_faces = src[0]['use_tris'] use_rh_faces = src[1]['use_tris'] use_faces = np.r_[use_lh_faces, lh_points.shape[0] + use_rh_faces] points *= 170 vertnos = [ np.r_[stc.lh_vertno, lh_points.shape[0] + stc.rh_vertno] for stc in stcs ] unique_vertnos = np.unique(np.concatenate(vertnos).ravel()) try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab from matplotlib.colors import ColorConverter color_converter = ColorConverter() f = mlab.figure(figure=fig_name, bgcolor=bgcolor, size=(600, 600)) mlab.clf() f.scene.disable_render = True surface = mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], use_faces, color=brain_color, opacity=opacity, **kwargs) import pylab as pl # Show time courses pl.figure(fig_number) pl.clf() colors = cycle(colors) logger.info("Total number of active sources: %d" % len(unique_vertnos)) if labels is not None: colors = [ colors.next() for _ in range(np.unique(np.concatenate(labels).ravel()).size) ] for v in unique_vertnos: # get indices of stcs it belongs to ind = [k for k, vertno in enumerate(vertnos) if v in vertno] is_common = len(ind) > 1 if labels is None: c = colors.next() else: # if vertex is in different stcs than take label from first one c = colors[labels[ind[0]][vertnos[ind[0]] == v]] mode = modes[1] if is_common else modes[0] scale_factor = scale_factors[1] if is_common else scale_factors[0] x, y, z = points[v] nx, ny, nz = normals[v] mlab.quiver3d(x, y, z, nx, ny, nz, color=color_converter.to_rgb(c), mode=mode, scale_factor=scale_factor) for k in ind: vertno = vertnos[k] mask = (vertno == v) assert np.sum(mask) == 1 linestyle = linestyles[k] pl.plot(1e3 * stc.times, 1e9 * stcs[k].data[mask].ravel(), c=c, linewidth=linewidth, linestyle=linestyle) pl.xlabel('Time (ms)', fontsize=18) pl.ylabel('Source amplitude (nAm)', fontsize=18) if fig_name is not None: pl.title(fig_name) if show: pl.show() surface.actor.property.backface_culling = True surface.actor.property.shading = True return surface
def rgba(self): r, g, b = ColorConverter().to_rgb(self.color) return (r, g, b, self.alpha)
def automatic_color(self): n = len(self.viewer.epocharrays) cmap = get_cmap('jet', n) for i, pEpoch in enumerate(self.viewer.paramEpochs.children()): color = [int(c * 255) for c in ColorConverter().to_rgb(cmap(i))] pEpoch.param('color').setValue(color)
def plot_dipole_locations(dipoles, trans, subject, subjects_dir=None, bgcolor=(1, 1, 1), opacity=0.3, brain_color=(1, 1, 0), fig_name=None, fig_size=(600, 600), mode='cone', scale_factor=0.1e-1, colors=None, verbose=None): """Plot dipole locations Only the location of the first time point of each dipole is shown. Parameters ---------- dipoles : list of instances of Dipole | Dipole The dipoles to plot. trans : dict The mri to head trans. subject : str The subject name corresponding to FreeSurfer environment variable SUBJECT. subjects_dir : None | str The path to the freesurfer subjects reconstructions. It corresponds to Freesurfer environment variable SUBJECTS_DIR. The default is None. bgcolor : tuple of length 3 Background color in 3D. opacity : float in [0, 1] Opacity of brain mesh. brain_color : tuple of length 3 Brain color. fig_name : str Mayavi figure name. fig_size : tuple of length 2 Mayavi figure size. mode : str Should be ``'cone'`` or ``'sphere'`` to specify how the dipoles should be shown. scale_factor : float The scaling applied to amplitudes for the plot. colors: list of colors | None Color to plot with each dipole. If None default colors are used. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). Returns ------- fig : instance of mlab.Figure The mayavi figure. Notes ----- .. versionadded:: 0.9.0 """ from mayavi import mlab from matplotlib.colors import ColorConverter color_converter = ColorConverter() trans = _get_trans(trans)[0] subjects_dir = get_subjects_dir(subjects_dir=subjects_dir, raise_error=True) fname = op.join(subjects_dir, subject, 'bem', 'inner_skull.surf') points, faces = read_surface(fname) points = apply_trans(trans['trans'], points * 1e-3) from .. import Dipole if isinstance(dipoles, Dipole): dipoles = [dipoles] if mode not in ['cone', 'sphere']: raise ValueError('mode must be in "cone" or "sphere"') if colors is None: colors = cycle(COLORS) fig = mlab.figure(size=fig_size, bgcolor=bgcolor, fgcolor=(0, 0, 0)) with warnings.catch_warnings(record=True): # FutureWarning in traits mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces, color=brain_color, opacity=opacity) for dip, color in zip(dipoles, colors): rgb_color = color_converter.to_rgb(color) with warnings.catch_warnings(record=True): # FutureWarning in traits mlab.quiver3d(dip.pos[0, 0], dip.pos[0, 1], dip.pos[0, 2], dip.ori[0, 0], dip.ori[0, 1], dip.ori[0, 2], opacity=1., mode=mode, color=rgb_color, scalars=dip.amplitude.max(), scale_factor=scale_factor) if fig_name is not None: mlab.title(fig_name) if fig.scene is not None: # safe for Travis fig.scene.x_plus_view() return fig
def plot_sparse_source_estimates(src, stcs, colors=None, linewidth=2, fontsize=18, bgcolor=(.05, 0, .1), opacity=0.2, brain_color=(0.7, ) * 3, show=True, high_resolution=False, fig_name=None, fig_number=None, labels=None, modes=('cone', 'sphere'), scale_factors=(1, 0.6), verbose=None, **kwargs): """Plot source estimates obtained with sparse solver Active dipoles are represented in a "Glass" brain. If the same source is active in multiple source estimates it is displayed with a sphere otherwise with a cone in 3D. Parameters ---------- src : dict The source space. stcs : instance of SourceEstimate or list of instances of SourceEstimate The source estimates (up to 3). colors : list List of colors linewidth : int Line width in 2D plot. fontsize : int Font size. bgcolor : tuple of length 3 Background color in 3D. opacity : float in [0, 1] Opacity of brain mesh. brain_color : tuple of length 3 Brain color. show : bool Show figures if True. high_resolution : bool If True, plot on the original (non-downsampled) cortical mesh. fig_name : Mayavi figure name. fig_number : Matplotlib figure number. labels : ndarray or list of ndarrays Labels to show sources in clusters. Sources with the same label and the waveforms within each cluster are presented in the same color. labels should be a list of ndarrays when stcs is a list ie. one label for each stc. modes : list Should be a list, with each entry being ``'cone'`` or ``'sphere'`` to specify how the dipoles should be shown. scale_factors : list List of floating point scale factors for the markers. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). **kwargs : kwargs Keyword arguments to pass to mlab.triangular_mesh. """ known_modes = ['cone', 'sphere'] if not isinstance(modes, (list, tuple)) or \ not all(mode in known_modes for mode in modes): raise ValueError('mode must be a list containing only ' '"cone" or "sphere"') if not isinstance(stcs, list): stcs = [stcs] if labels is not None and not isinstance(labels, list): labels = [labels] if colors is None: colors = COLORS linestyles = ['-', '--', ':'] # Show 3D lh_points = src[0]['rr'] rh_points = src[1]['rr'] points = np.r_[lh_points, rh_points] lh_normals = src[0]['nn'] rh_normals = src[1]['nn'] normals = np.r_[lh_normals, rh_normals] if high_resolution: use_lh_faces = src[0]['tris'] use_rh_faces = src[1]['tris'] else: use_lh_faces = src[0]['use_tris'] use_rh_faces = src[1]['use_tris'] use_faces = np.r_[use_lh_faces, lh_points.shape[0] + use_rh_faces] points *= 170 vertnos = [ np.r_[stc.lh_vertno, lh_points.shape[0] + stc.rh_vertno] for stc in stcs ] unique_vertnos = np.unique(np.concatenate(vertnos).ravel()) from mayavi import mlab from matplotlib.colors import ColorConverter color_converter = ColorConverter() f = mlab.figure(figure=fig_name, bgcolor=bgcolor, size=(600, 600)) mlab.clf() if mlab.options.backend != 'test': f.scene.disable_render = True with warnings.catch_warnings(record=True): # traits warnings surface = mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], use_faces, color=brain_color, opacity=opacity, **kwargs) import matplotlib.pyplot as plt # Show time courses plt.figure(fig_number) plt.clf() colors = cycle(colors) logger.info("Total number of active sources: %d" % len(unique_vertnos)) if labels is not None: colors = [ advance_iterator(colors) for _ in range(np.unique(np.concatenate(labels).ravel()).size) ] for idx, v in enumerate(unique_vertnos): # get indices of stcs it belongs to ind = [k for k, vertno in enumerate(vertnos) if v in vertno] is_common = len(ind) > 1 if labels is None: c = advance_iterator(colors) else: # if vertex is in different stcs than take label from first one c = colors[labels[ind[0]][vertnos[ind[0]] == v]] mode = modes[1] if is_common else modes[0] scale_factor = scale_factors[1] if is_common else scale_factors[0] if (isinstance(scale_factor, (np.ndarray, list, tuple)) and len(unique_vertnos) == len(scale_factor)): scale_factor = scale_factor[idx] x, y, z = points[v] nx, ny, nz = normals[v] with warnings.catch_warnings(record=True): # traits mlab.quiver3d(x, y, z, nx, ny, nz, color=color_converter.to_rgb(c), mode=mode, scale_factor=scale_factor) for k in ind: vertno = vertnos[k] mask = (vertno == v) assert np.sum(mask) == 1 linestyle = linestyles[k] plt.plot(1e3 * stcs[k].times, 1e9 * stcs[k].data[mask].ravel(), c=c, linewidth=linewidth, linestyle=linestyle) plt.xlabel('Time (ms)', fontsize=18) plt.ylabel('Source amplitude (nAm)', fontsize=18) if fig_name is not None: plt.title(fig_name) plt_show(show) surface.actor.property.backface_culling = True surface.actor.property.shading = True return surface
def visualize_classification_prediction(estimator, x_train, y_train, show=False, block_on_end=False, **kwargs): if x_train.shape[1] > 2: print('Support only 2D datasets') return if len(np.unique(y_train)) > 5: print('Not support for n_classes > 5') return grid_size = 500 if 'grid_size' not in kwargs else kwargs['grid_size'] marker_size = 500 if 'marker_size' not in kwargs else kwargs['marker_size'] top = None if 'top' not in kwargs else kwargs['top'] bottom = None if 'bottom' not in kwargs else kwargs['bottom'] left = None if 'left' not in kwargs else kwargs['left'] right = None if 'right' not in kwargs else kwargs['right'] epoch = kwargs['epoch'] if left is None: left = np.min(x_train, axis=0)[0] if right is None: right = np.max(x_train, axis=0)[0] if top is None: top = np.max(x_train, axis=0)[1] if bottom is None: bottom = np.min(x_train, axis=0)[1] x_axis = np.linspace(left, right, grid_size) y_axis = np.linspace(bottom, top, grid_size) x_axis_v, y_axis_v = np.meshgrid(x_axis, y_axis) x_test = np.vstack((x_axis_v.ravel(), y_axis_v.ravel())) x_test = x_test.T x_scale = (right - left) / grid_size y_scale = (top - bottom) / grid_size print('Drawing at epoch {}...'.format(epoch)) n_test = x_test.shape[0] y_test = estimator.predict(x_test) y_test_zidx = y_test.astype(int).copy() y_train_zidx = estimator.label_encoder.inverse_transform(y_train.astype(int)) img = np.zeros((n_test, 3)) n_classes = estimator.num_classes bg_colors_hex = np.array(["#A6CEE3", "#B2DF8A", "#FB9A99", "#FDBF6F", "#CAB2D6"]) # Bugs fore_colors_hex = np.array(["#1F78B4", "#33A02C", "#E31A1C", "#FF7F00", "#6A3D9A"]) # Bugs converter = ColorConverter() bg_colors = np.zeros((len(bg_colors_hex), 3)) for ci in range(len(fore_colors_hex)): bg_colors[ci, :] = converter.to_rgb(bg_colors_hex[ci]) for ci in range(n_classes): img[y_test_zidx == ci, :] = bg_colors[ci] img = img.reshape((grid_size, grid_size, 3)) plt.imshow(img) plt.scatter((x_train[:, 0] - left) / x_scale, (x_train[:, 1] - bottom) / y_scale, s=marker_size, color=fore_colors_hex[y_train_zidx.astype(int)]) axes = plt.gca() axes.set_xlim([0, grid_size]) axes.set_ylim([0, grid_size]) # plt.legend() kwargs['ax'] = axes if show: plt.show(block=block_on_end)
import win32com.client from numpy import * from pylab import * import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib.colors import ColorConverter import matplotlib.text as text colorConverter = ColorConverter() import re class DSS: # """ # [email protected] 2008-11-17 # comments: [email protected] 2009-10-30 def __init__(self, filename=""): """ Inputs: filename - string - DSS input file Side effects: start DSS via COM Contains the following DSS COM objects: engine text circuit """ # start an embedded DSS engine through COM # note: OpenDSSEngine.dll must already be registered self.engine = win32com.client.Dispatch("OpenDSSEngine.DSS")
def automatic_color(self): n = len(self.viewer.spiketrains) cmap = get_cmap('jet', n) for i, p in enumerate(self.viewer.paramSpikeTrains.children()): color = [int(c * 255) for c in ColorConverter().to_rgb(cmap(i))] p.param('color').setValue(color)
def set_color(self, label, rgb): if isinstance(rgb, six.string_types): rgb = ColorConverter().to_rgb(rgb) self.layers[label]['color'] = np.asarray(rgb) self._update()
def plot(ax, signals, name_map=None, t_final=None): if t_final is None: #start by finding the maximum time t_final = get_t_final(signals) t_final *= 1.001 channels = list(signals.items()) if name_map: channels.sort(key=lambda v: -name_map[v[0]]['order']) get_label = lambda n: name_map[n]['name'] get_xscale = lambda n: float(name_map[n]['dt_clk']) #strip units get_yscale = lambda n: name_map[n]['yscale'] else: channels.sort(key=lambda v: v[0]) # reverse lexical sort get_label = lambda n: n get_xscale = lambda n: 1.0 # scaled by unity by default # offset by 0.0 and scaled by unity by default: get_yscale = lambda n: (0.0, 1.0) def apply_yscale(y, yscale): """ Given an array of values y, where y is a subset of Y, we need to apply a scaling like: y = (y - min(Y)) / (max(Y) - min(Y)) """ if yscale[0] != 0: # 'if' is so we can avoid looping if not necessary y -= yscale[0] if yscale[1] != 1.0: # 'if' is so we can avoid looping if not necessary y *= yscale[1] return y cconv = ColorConverter() ax.clear() labels = list() i = 0 group_lines = dict() ylim = 1e300, 1e-300 for chname, grp_data in channels: labels.append(get_label(chname)) xscale = get_xscale(chname) yscale = get_yscale(chname) x0 = None y0 = None # sort groups by time in last (time,value) element groups = sorted(grp_data.items(), key=lambda grp_encdata: grp_encdata[1][1][-1][0]) for grp, (encoding, data) in groups: xg, yg, x0, y0 = mkxy(encoding, data, x0, y0) xg *= xscale apply_yscale(yg, yscale) ylim = min(ylim[0], yg.min()), max(ylim[1], yg.max()) group_lines[(grp, chname)] = ax.plot(xg, yg, color=fc(i), linewidth=2)[0] # By definition, each final transition is supposed to be honored as a fixed # value. This final data point just ensures that this hold is plotted for # each channel until all channels have finished. x0 *= xscale y0 = apply_yscale(y0, yscale) x1 = t_final y1 = y0 group_lines[((-1,), chname)] = \ ax.plot( [x0, x1], [y0, y1], color=fc(i), linewidth=2 )[0] i += 1 #ax.set_xlabel('Time (s)') #ax.set_yticks( np.r_[0.5:i] ) #ax.set_yticklabels(labels) #ax.legend( labels, loc=(-0.25,0) ) dy = (ylim[1] - ylim[0]) * .1 ax.set_ylim(float(ylim[0] - dy), float(ylim[1] + dy)) ax.grid(True) return (t_final, ax.get_ylim()), group_lines
def yearplot( data, year=None, how="sum", vmin=None, vmax=None, cmap=None, fillcolor="whitesmoke", linewidth=1, linecolor=None, daylabels=calendar.day_abbr[:], dayticks=True, monthlabels=calendar.month_abbr[1:], monthticks=True, ax=None, **kwargs ): """ Plot one year from a timeseries as a calendar heatmap. Parameters ---------- data : Series Data for the plot. Must be indexed by a DatetimeIndex. year : integer Only data indexed by this year will be plotted. If `None`, the first year for which there is data will be plotted. how : string Method for resampling data by day. If `None`, assume data is already sampled by day and don't resample. Otherwise, this is passed to Pandas `Series.resample`. vmin, vmax : floats Values to anchor the colormap. If `None`, min and max are used after resampling data by day. cmap : matplotlib colormap name or object The mapping from data values to color space. fillcolor : matplotlib color Color to use for days without data. linewidth : float Width of the lines that will divide each day. linecolor : color Color of the lines that will divide each day. If `None`, the axes background color is used, or 'white' if it is transparent. daylabels : list Strings to use as labels for days, must be of length 7. dayticks : list or int or bool If `True`, label all days. If `False`, don't label days. If a list, only label days with these indices. If an integer, label every n day. monthlabels : list Strings to use as labels for months, must be of length 12. monthticks : list or int or bool If `True`, label all months. If `False`, don't label months. If a list, only label months with these indices. If an integer, label every n month. ax : matplotlib Axes Axes in which to draw the plot, otherwise use the currently-active Axes. kwargs : other keyword arguments All other keyword arguments are passed to matplotlib `ax.pcolormesh`. Returns ------- ax : matplotlib Axes Axes object with the calendar heatmap. Examples -------- By default, `yearplot` plots the first year and sums the values per day: .. plot:: :context: close-figs calmap.yearplot(events) We can choose which year is plotted with the `year` keyword argment: .. plot:: :context: close-figs calmap.yearplot(events, year=2015) The appearance can be changed by using another colormap. Here we also use a darker fill color for days without data and remove the lines: .. plot:: :context: close-figs calmap.yearplot(events, cmap='YlGn', fillcolor='grey', linewidth=0) The axis tick labels can look a bit crowded. We can ask to draw only every nth label, or explicitely supply the label indices. The labels themselves can also be customized: .. plot:: :context: close-figs calmap.yearplot(events, monthticks=3, daylabels='MTWTFSS', dayticks=[0, 2, 4, 6]) """ if year is None: year = data.index.sort_values()[0].year if how is None: # Assume already sampled by day. by_day = data else: # Sample by day. if _pandas_18: by_day = data.resample("D").agg(how) else: by_day = data.resample("D", how=how) # Min and max per day. if vmin is None: vmin = by_day.min() if vmax is None: vmax = by_day.max() if ax is None: ax = plt.gca() if linecolor is None: # Unfortunately, linecolor cannot be transparent, as it is drawn on # top of the heatmap cells. Therefore it is only possible to mimic # transparent lines by setting them to the axes background color. This # of course won't work when the axes itself has a transparent # background so in that case we default to white which will usually be # the figure or canvas background color. linecolor = ax.get_facecolor() if ColorConverter().to_rgba(linecolor)[-1] == 0: linecolor = "white" # Filter on year. by_day = by_day[str(year)] # Add missing days. by_day = by_day.reindex( pd.date_range(start=str(year), end=str(year + 1), freq="D")[:-1] ) # Create data frame we can pivot later. by_day = pd.DataFrame( { "data": by_day, "fill": 1, "day": by_day.index.dayofweek, "week": by_day.index.isocalendar().week, } ) # There may be some days assigned to previous year's last week or # next year's first week. We create new week numbers for them so # the ordering stays intact and week/day pairs unique. by_day.loc[(by_day.index.month == 1) & (by_day.week > 50), "week"] = 0 by_day.loc[(by_day.index.month == 12) & (by_day.week < 10), "week"] = ( by_day.week.max() + 1 ) # Pivot data on day and week and mask NaN days. (we can also mask the days with 0 counts) plot_data = by_day.pivot("day", "week", "data").values[::-1] plot_data = np.ma.masked_where(np.isnan(plot_data), plot_data) # Do the same for all days of the year, not just those we have data for. fill_data = by_day.pivot("day", "week", "fill").values[::-1] fill_data = np.ma.masked_where(np.isnan(fill_data), fill_data) # Draw background of heatmap for all days of the year with fillcolor. ax.pcolormesh(fill_data, vmin=0, vmax=1, cmap=ListedColormap([fillcolor])) # Draw heatmap. kwargs["linewidth"] = linewidth kwargs["edgecolors"] = linecolor ax.pcolormesh(plot_data, vmin=vmin, vmax=vmax, cmap=cmap, **kwargs) # Limit heatmap to our data. ax.set(xlim=(0, plot_data.shape[1]), ylim=(0, plot_data.shape[0])) # Square cells. ax.set_aspect("equal") # Remove spines and ticks. for side in ("top", "right", "left", "bottom"): ax.spines[side].set_visible(False) ax.xaxis.set_tick_params(which="both", length=0) ax.yaxis.set_tick_params(which="both", length=0) # Get indices for monthlabels. if monthticks is True: monthticks = range(len(monthlabels)) elif monthticks is False: monthticks = [] elif isinstance(monthticks, int): monthticks = range(len(monthlabels))[monthticks // 2 :: monthticks] # Get indices for daylabels. if dayticks is True: dayticks = range(len(daylabels)) elif dayticks is False: dayticks = [] elif isinstance(dayticks, int): dayticks = range(len(daylabels))[dayticks // 2 :: dayticks] ax.set_xlabel("") timestamps = [] # Month borders, from https://github.com/rougier/calendar-heatmap/blob/master/github-activity.py, license BSD xticks, labels = [], [] for month in range(1, 13): first = datetime.datetime(year, month, 1) last = first + relativedelta(months=1, days=-1) # Monday on top y0 = 6 - first.weekday() y1 = 6 - last.weekday() start = datetime.datetime(year, 1, 1).weekday() x0 = (int(first.strftime("%j")) + start - 1) // 7 x1 = (int(last.strftime("%j")) + start - 1) // 7 P = [(x0, y0 + 1), (x0, 0), (x1, 0), (x1, y1), (x1 + 1, y1), (x1 + 1, 7), (x0 + 1, 7), (x0 + 1, y0 + 1)] xticks.append(x0 + (x1 - x0 + 1) / 2) labels.append(first.strftime("%b")) poly = Polygon(P, edgecolor="black", facecolor="None", linewidth=1, zorder=20, clip_on=False) ax.add_artist(poly) ax.set_xticks(xticks) ax.set_xticklabels(labels) ax.set_ylabel("") ax.yaxis.set_ticks_position("right") ax.set_yticks([6 - i + 0.5 for i in dayticks]) ax.set_yticklabels( [daylabels[i] for i in dayticks], rotation="horizontal", va="center" ) return ax
xr.append([k[0], k[1]]) else: xb.append([k[0], k[1]]) xr = np.array(xr) xb = np.array(xb) plt.scatter(xr[:,0], xr[:,1], c='r', marker='+') plt.scatter(xb[:,0], xb[:,1], c='b', marker='o') yTrain = np.reshape(yTrain, [-1,1]) print('loss:\n', sess.run(loss, feed_dict={x:xTrain, y:yTrain,keep_prob:1.0})) nb_of_xs = 200 xs1 = np.linspace(-1, 8, nb_of_xs) xs2 = np.linspace(-1, 8, nb_of_xs) xx, yy = np.meshgrid(xs1, xs2) #初始和填充classification plane classification_plane = np.zeros((nb_of_xs, nb_of_xs)) for i in range(nb_of_xs): for j in range(nb_of_xs): classification_plane[i,j] = sess.run(y_pred, feed_dict={x:[[ xx[i,j],yy[i,j] ]],keep_prob:1.0}) classification_plane[i,j] = int(classification_plane[i,j]+0.5) #创建一个color map用来显示每一个格子的分类颜色 cmap = ListedColormap([ ColorConverter.to_rgba('r', alpha=0.3), ColorConverter.to_rgba('b', alpha=0.3) ]) plt.contourf(xx, yy, classification_plane, cmap=cmap) plt.show()
errors_upper = [ys[i] + std_errors[i] for i in range(len(ys))] ymax = max(ymax, max(errors_upper)) ax.errorbar( error_xs, error_ys, yerr=yerr, ecolor=adata.color, fmt="none", capthick=2, ) if args.stddev: ys_lower = [y - s for y, s in zip(ys, std_errors)] ys_upper = [y + s for y, s in zip(ys, std_errors)] cc = ColorConverter() c = cc.to_rgba(adata.color, .15) ax.fill_between(xs, ys_lower, ys_upper, facecolor=c, linewidth=0) ylabel = { 'treward': 'Total Reward', 'time': 'Total Processing Time (ms)', 'ereward_mean': 'Cumulative Mean Reward', 'treward_mean': 'Average Reward Per Timestep', 'esteps_mean': 'Average Episode Length', 'esteps': 'Episode Length', }[args.metric] ax.set_ylabel(ylabel) ax.set_xlabel('Episode') if args.domain_complexity is None: ax.set_title('%s per Episode' % ylabel)
import argparse rcParams.update({'figure.autolayout': True}) band_colors = {'U':'Violet', 'B':'Blue', 'V':'Green', 'R':'Red', 'I':'Orange', 'J':'Pink',\ 'H':'Brown', 'K':'Gray', 'u': 'Violet', 'g':'Green', 'r': 'Orange', 'i':'Red', 'z': 'Brown', 'q': 'Yellow', 'y':'Black'} markerList = ['o', 's', 'p', '*', '^', 'v', 'D', 'x', '<', '>', 8, '+', '|'] nights_per_minute = 20 #nr. nights animated in one minute ms_per_night = 60 * 1000 / nights_per_minute #nr. of miliseconds that each night lasts in the animations one_night = 24 * 60 * 60. #nr. of seconds in a night Bigjumpfactor = 3. #The factor by which large jumps in frame rate should be divided to keep the movie length reasonable myCC = ColorConverter() class AnData: """ This class unpacks the data from the file that TSS output The output file contains a row for every transient observation So, if there are three Supernovae Iae observed, each with five observations, 3*5=15 rows are reserved for supernovae Iae Parameters ---------- datafile : str Name of the file that TSS output that will be animated bandList : list List of the colorfilters that need to be animated
class AgrLine: fmt = """hidden {hidden} type {type} legend "{label}" line linestyle {linestyle} line linewidth {linewidth} line color {color} symbol {marker} symbol color {markeredgecolor} symbol fill color {markerfacecolor} symbol fill pattern {markerfill} symbol linewidth {linewidth} """ width_scale = 2 cc = ColorConverter() linestyles = {'None': 0, '-': 1, ':': 2, '--': 3, '-.': 5} markers = defaultdict( lambda: 1, {'': 0, 'None': 0, 'o': 1, 's': 2, 'd': 3, '^': 4, '<': 5, 'v': 6, '>': 7, '+': 8, 'x': 9, '*': 10} ) fillstyles = ('none', 'full', 'right', 'left', 'bottom', 'top') colors = ['white', 'black'] def color_index(col): if col not in AgrLine.colors: AgrLine.colors.append(col) return AgrLine.colors.index(col) @property def data(self): o = '@type xy\n' for x, y in self.line.get_xydata(): o += '{} {}\n'.format(x, y) o += '&' return o def get_label(self): lbl = self.line.get_label() self.label = latex_to_xmgrace(lbl) if not lbl.startswith('_line') else '' def get_linestyle(self): self.linestyle = self.linestyles[self.line.get_linestyle()] def get_linewidth(self): self.linewidth = self.line.get_linewidth() * self.width_scale def get_color(self): self.color = AgrLine.color_index(self.line.get_color()) def get_marker(self): mk = self.line.get_marker() self.marker = self.markers[mk] if mk in self.markers else 1 mfc = self.line.get_markerfacecolor() self.markerfacecolor = AgrLine.color_index(mfc) mec = self.line.get_markeredgecolor() self.markeredgecolor = AgrLine.color_index(mec) self.markeredgewidth = self.line.get_markeredgewidth() * self.width_scale self.markerfill = self.fillstyles.index(self.line.get_fillstyle()) def __init__(self, line, agr_axis): self.agr_axis = agr_axis self.line = line self.hidden = 'false' self.type = 'xy' # run all get_ methods for d in dir(self): if d.startswith('get_'): getattr(self, d)() sanitize_strings(self.__dict__) def __str__(self): return self.fmt.format(**self.__dict__)