コード例 #1
0
ファイル: manual_sort.py プロジェクト: belevtsoff/SpikeSort
    def __init__(self, ax, data,labels=None, color_on='r', color_off='k'):
        self.axes = ax
        self.canvas = ax.figure.canvas
        self.data = data
        self.call_list = []

        self.Nxy = data.shape[0]
        self.color_on = colorConverter.to_rgba(color_on)
        self.color_off = colorConverter.to_rgba(color_off)

        facecolors = [self.color_on for _ in range(self.Nxy)]
        fig = ax.figure
        self.collection = RegularPolyCollection(
            fig.dpi, 6, sizes=(1,),
            facecolors=facecolors,
            edgecolors=facecolors,
            offsets = self.data,
            transOffset = ax.transData)

        ax.add_collection(self.collection, autolim=True)
        ax.autoscale_view()
        
        if labels is not None:
            ax.set_xlabel(labels[0])
            ax.set_ylabel(labels[1])
        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
        self.ind = None
        self.canvas.draw()
コード例 #2
0
ファイル: roi.py プロジェクト: pganssle/pyCEST
    def __init__(self, axis, **poly_kwargs):
        """
        Supply an axis on which to plot the boxes
        """
        self.ax = axis
        self.rois = []
        self.selector = None

        dflt_kwargs = dict(fc='#0000b3',
                           fa=0.25,
                           ec='k',
                           ea=1.0,
                           lw=1)

        dflt_kwargs.update(poly_kwargs)
        poly_kwargs = dflt_kwargs

        # Allow 'face_alpha' / 'fa' and 'edge_alpha' / 'ea'
        face_alpha = poly_kwargs.pop('fa', None)
        face_alpha = poly_kwargs.pop('face_alpha', face_alpha)

        face_color = poly_kwargs.pop('fc', None)
        face_color = poly_kwargs.pop('face_color', face_color)
        poly_kwargs['fc'] = colorConverter.to_rgba(face_color, alpha=face_alpha)

        edge_alpha = poly_kwargs.pop('ea', None)
        edge_alpha = poly_kwargs.pop('edge_alpha', edge_alpha)

        edge_color = poly_kwargs.pop('ec', None)
        edge_color = poly_kwargs.pop('edge_color', edge_color)
        poly_kwargs['ec'] = colorConverter.to_rgba(edge_color, alpha=edge_alpha)

        self.poly_kwargs = poly_kwargs
コード例 #3
0
def index_bar(ax, vals,
              facecolor='b', edgecolor='l',
              width=4, alpha=1.0, ):
    """
    Add a bar collection graph with height vals (-1 is missing).
    ax          : an Axes instance to plot to
    width       : the bar width in points
    alpha       : bar transparency
    """
    facecolors = (colorConverter.to_rgba(facecolor, alpha),)
    edgecolors = (colorConverter.to_rgba(edgecolor, alpha),)
    right = width/2.0
    left = -width/2.0
    bars = [ ( (left, 0), (left, v), (right, v), (right, 0)) for v in vals if v != -1 ]
    sx = ax.figure.dpi * (1.0/72.0)  # scale for points
    sy = ax.bbox.height / ax.viewLim.height
    barTransform = Affine2D().scale(sx,sy)
    offsetsBars = [ (i, 0) for i,v in enumerate(vals) if v != -1 ]
    barCollection = PolyCollection(bars,
                                   facecolors   = facecolors,
                                   edgecolors   = edgecolors,
                                   antialiaseds = (0,),
                                   linewidths   = (0.5,),
                                   offsets      = offsetsBars,
                                   transOffset  = ax.transData,
                                   )
    barCollection.set_transform(barTransform)
    minpy, maxx = (0, len(offsetsBars))
    miny = 0
    maxy = max([v for v in vals if v!=-1])
    corners = (minpy, miny), (maxx, maxy)
    ax.update_datalim(corners)
    ax.autoscale_view()
    ax.add_collection(barCollection)
    return barCollection
コード例 #4
0
ファイル: map.py プロジェクト: ewilkinson/CS689_FinalProj
    def show_window(self, subwindow):
        obstable_img = np.transpose(subwindow[0, :, :])
        alt_var_img = np.transpose(subwindow[1, :, :])

        # generate the colors for your colormap

        color1 = colorConverter.to_rgba('white')
        color2 = colorConverter.to_rgba('blue')

        # make the colormaps
        cmap1 = mpl.colors.LinearSegmentedColormap.from_list('my_cmap', ['white', 'black'], 256)
        cmap2 = mpl.colors.LinearSegmentedColormap.from_list('my_cmap2', [color1, color2], 256)

        cmap2._init()  # create the _lut array, with rgba values

        # create your alpha array and fill the colormap with them.
        # here it is progressive, but you can create whathever you want
        alphas = np.linspace(0., 1.0, cmap2.N + 3)
        cmap2._lut[:, -1] = alphas

        plt.figure()
        img3 = plt.imshow(obstable_img, interpolation='none', vmin=0, vmax=1, cmap=cmap1, origin='lower')
        plt.hold(True)
        img2 = plt.imshow(alt_var_img, interpolation='none', vmin=0, vmax=1, cmap=cmap2, origin='lower')
        plt.colorbar()
        plt.hold(False)
        plt.show()
コード例 #5
0
ファイル: __init__.py プロジェクト: tkf/mplchaco
    def _plot_from_line(plot, suffix, line):
        """
        Plot lines in Chaco Plot object `plot` given MPL Line2D `line`.
        """
        xname = "lx_{0}".format(suffix)
        yname = "ly_{0}".format(suffix)
        plot.data.set_data(xname, line.get_xdata())
        plot.data.set_data(yname, line.get_ydata())

        ls = line.get_linestyle()
        if ls != "None":
            plot.plot(
                (xname, yname),
                line_style=line_trans.get(ls, "solid"),
                color=colorConverter.to_rgba(line.get_color()))

        marker = line.get_marker()
        if marker != "None":
            chaco_marker = marker_trans.get(marker, "circle")
            if chaco_marker == 'down triangle':
                # Workaround the bug in Chaco shell.
                # (https://github.com/enthought/chaco/issues/70)
                chaco_marker = 'inverted_triangle'
            plot.plot(
                (xname, yname),
                type="scatter",
                marker=chaco_marker,
                color=colorConverter.to_rgba(line.get_markerfacecolor()))
コード例 #6
0
ファイル: plot_tools.py プロジェクト: claria/plot
def plot_band(obj=None, step=False, emptybins=True, ax=None, **kwargs):
    """ Produce an errorbar plots with or without connecting lines.

    Args:
        obj: Mplobj representation of a root object.
        ax: Axis to plot on. If not specified current global axis will be used.
        x_err: If True, x errorbars will be plotted.
        yerr: If True, y errorbars will be plotted.
        emptybins: Not Implemented. Supposed to ignore/plot empty bins.
    """
    # Convert root object to mpl readable object
    obj = R2npObject1D(obj)
    # if no axis passed use current global axis
    if ax is None:
        ax = plt.gca()

    x = obj.x
    y = obj.y


    y_errl = obj.yerrl
    y_erru = obj.yerru

    if step:
        x = steppify_bin(obj.xbinedges, isx=True)
        y = steppify_bin(y)
        y_errl = steppify_bin(y_errl)
        y_erru = steppify_bin(y_erru)

    y_le = y - y_errl
    y_ue = y + y_erru
    if 'clip_vals' in kwargs:
        y_le = np.clip(y - y_errl, kwargs['clip_vals'][0], kwargs['clip_vals'][1])
        y_ue = np.clip(y + y_erru, kwargs['clip_vals'][0], kwargs['clip_vals'][1])

    if kwargs['facecolor'] == 'none':
        fill = False
    else:
        fill = True

    kwargs['facecolor'] = colorConverter.to_rgba(kwargs['facecolor'], kwargs.get('alpha', 1.0))
    kwargs['edgecolor'] = colorConverter.to_rgba(kwargs['edgecolor'], kwargs.get('edgealpha', 1.0))

    # plot without hatch
    fill_between_kwargs = {k: v for k, v in kwargs.items() if
                           k in ['label', 'facecolor', 'edgecolor', 'zorder', 'rasterized', 'linewidth']}

    artist = ax.fill_between(x, y_le, y_ue, **fill_between_kwargs)

    # work around okular bug present when hatch+color is plotted (plot 
    if 'hatch' in kwargs:
        fill_between_kwargs2 = {k: v for k, v in kwargs.items() if
                               k in ['label', 'edgecolor', 'zorder', 'hatch', 'rasterized', 'linewidth']}
        artist = ax.fill_between(x, y_le, y_ue, color='none', **fill_between_kwargs2)

    p = matplotlib.patches.Rectangle((0, 0), 0, 0, hatch=kwargs.get('hatch', ''), **fill_between_kwargs)
    ax.add_patch(p)

    return p
コード例 #7
0
ファイル: contracts.py プロジェクト: PennyQ/glue
 def color(value):
     """
     A valid matplotlib color
     """
     from matplotlib.colors import colorConverter
     try:
         colorConverter.to_rgba(value)
     except ValueError:
         return False
コード例 #8
0
def draw3DComplex(K, axes, dimensions = [0,1,2,3]):
	if isinstance(K, CH.CubicalComplex):
		if 0 in dimensions:
			points = [map(lambda x:x[0], cube.intervals) for cube in K(0) if not K.isCritical(cube)]
			if points:
				x, y, z = map(np.array, zip(*points))
				axes.scatter(y, z, -x, c='b', marker='o')
			criticalPoints = [map(lambda x:x[0], cube.intervals) for cube in K(0) if K.isCritical(cube)]
			if criticalPoints:
				x, y, z = map(np.array, zip(*criticalPoints))
				axes.scatter(y, z, -x, c='r', marker='o')
			
		r1 = 0.85
		r3 = 0.8
		a1 = 0.9
		a2 = 0.8

		if 1 in dimensions:
			for edge in K(1):
				c = 'g-' if K.isCritical(edge) else 'b--'
				points = list(product(*map(set, edge.intervals)))
				V = [homothetic(edge.center, r1, P) for P in points]
				x, y, z = map(np.array, zip(*V))
				axes.plot(y, z, -x, c, linewidth=2, )

		if 2 in dimensions:
			for face in K(2):
				points = list(product(*map(set, face.intervals)))
				V = [homothetic(face.center, r1, P) for P in points]
				x, y, z = map(np.array, zip(*V))
				X, Y, Z = map(lambda x: x.copy(), [x, y, z])
				X[2], X[3] = x[3], x[2]
				Y[2], Y[3] = y[3], y[2]
				Z[2], Z[3] = z[3], z[2]
				poly = Poly3DCollection(
					[zip(Y, Z, -X)], 
					facecolor=colorConverter.to_rgba('g', a2))
				axes.add_collection3d(poly)

		if 3 in dimensions:
			for cube in K(3):
				for face in cube.border():
					points = list(product(*map(set, face.intervals)))
					V = [homothetic(cube.center, r3, P) for P in points]
					x, y, z = map(np.array, zip(*V))
					X, Y, Z = map(lambda x: x.copy(), [x, y, z])
					X[2], X[3] = x[3], x[2]
					Y[2], Y[3] = y[3], y[2]
					Z[2], Z[3] = z[3], z[2]
					poly = Poly3DCollection(
						[zip(Y, Z, -X)], 
						facecolor=colorConverter.to_rgba('r', 1))
					axes.add_collection3d(poly)
	elif isinstance(K, ACH.CubicalComplex):
		draw3DComplex(K.toCubicalComplex(), axes, dimension)		
コード例 #9
0
ファイル: utils.py プロジェクト: codybushnell/plotly.py
def export_color(color):
    """Convert matplotlib color code to hex color or RGBA color"""
    if color is None or colorConverter.to_rgba(color)[3] == 0:
        return 'none'
    elif colorConverter.to_rgba(color)[3] == 1:
        rgb = colorConverter.to_rgb(color)
        return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
    else:
        c = colorConverter.to_rgba(color)
        return "rgba(" + ", ".join(str(int(np.round(val * 255)))
                                        for val in c[:3])+', '+str(c[3])+")"
コード例 #10
0
ファイル: axes3d.py プロジェクト: ranjithtenz/cis530
    def _shade_colors(self, color, normals):
        """
        Shade *color* using normal vectors given by *normals*.
        *color* can also be an array of the same length as *normals*.
        """

        shade = []
        for n in normals:
            n = n / proj3d.mod(n)
            shade.append(np.dot(n, [-1, -1, 0.5]))

        shade = np.array(shade)
        mask = ~np.isnan(shade)

        if len(shade[mask]) > 0:
            norm = Normalize(min(shade[mask]), max(shade[mask]))
            if art3d.iscolor(color):
                color = color.copy()
                color[3] = 1
                colors = [color * (0.5 + norm(v) * 0.5) for v in shade]
            else:
                colors = [np.array(colorConverter.to_rgba(c)) * (0.5 + norm(v) * 0.5) for c, v in zip(color, shade)]
        else:
            colors = color.copy()

        return colors
コード例 #11
0
def poly3d(df, elev=0, azim=0, **pltkwds):
    ''' Written by evelyn, updated by Adam 12/1/12.'''

    xlabel, ylabel, title, pltkwds=pu.smart_label(df, pltkwds)    

    zlabel_def=''         
    zlabel=pltkwds.pop('zlabel', zlabel_def)   
    zs=df.columns

    verts=[zip(df.index, df[col]) for col in df]  #don't have to say df.columns
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
       
 ### Convert verts(type:list) to poly(type:mpl_toolkits.mplot3d.art3d.Poly3DCollection)  
 ### poly used in plotting function ax.add_collection3d to do polygon plot    
    cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6)
    poly = PolyCollection((verts), facecolors = [cc('b'), cc('g'), cc('r'),
                        cc('y'),cc('m'), cc('c'), cc('b'),cc('g'),cc('r'), cc('y')])
    poly.set_alpha(0.2)  
    
 ### zdir is the direction used to plot,here we use time so y axis
    ax.add_collection3d(poly, zs=zs, zdir='x')        
    ax.set_xlabel(xlabel) 
    ax.set_ylabel(ylabel)  #Y
    ax.set_zlabel(zlabel)   #data     
    ax.set_title(title)       

    ax.set_ylim3d(min(df.index), max(df.index))
    ax.set_xlim3d(min(df.columns), max(df.columns))    #x 
    ax.set_zlim3d(min(df.min()), max(df.max()))  #How to get absolute min/max of df values
    
    ax.view_init(elev, azim) 

    return ax
コード例 #12
0
def plot4MainDir(degVector):
    fourDirVector = allDeg24Directions(degVector['Value'])
    pHours = 24 # periodo considerado
    sampling = 60 # 10min de amostragem
    base = pHours*60/sampling
    totDays = len(fourDirVector)/base  # Dias multiplo de 5, para graficos poly 3d
    days  = np.arange(totDays)+1
    hours = np.arange(0,pHours*60,sampling)
    meshTime, indices = np.meshgrid(hours, days)
    meshProfile = np.zeros(meshTime.shape)
    profileList = []
    ii = 1
    for i in range(totDays):
        dataPeriod = fourDirVector[i*base:ii*base]
        profileList.append( dataPeriod )
        ii +=1
    profileMatrix = np.array(profileList)
    for i in range( indices.shape[0] ):
        for j in range( indices.shape[1] ):
            meshProfile[(i,j)] = profileMatrix[(i,j)]

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = meshTime
    Y = indices
    Z = meshProfile
    ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='coolwarm', alpha=0.8) # ou a linha abaixo
    ax.set_xlabel('minutos')
    ax.set_ylabel('dia')
    ax.set_zlabel(r'$^oC$')

    # Visao apenas dos perfis
    fig2 = plt.figure()
    ax2 = fig2.gca(projection='3d')
    cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6)
    verts = []
    cs = [cc('r'), cc('g'), cc('b'), cc('y'), cc('c')]*(totDays/5)
    k = 0
    for d in days:
        verts.append(list(zip(hours, meshProfile[k])))
        k += 1
    poly = PolyCollection(verts, facecolors = cs)
    poly.set_alpha(0.7)
    ax2.add_collection3d(poly, zs=days, zdir='y')

    """ OK! Mostra grafico de barras
    cs = ['r', 'g', 'b', 'y','c']*(totDays/5)
    k = 0
    for c, d in zip(cs, days):
        cc = [c]*len(hours)
        ax2.bar(hours, meshProfile[k], zs=d, zdir='y', color=cc, alpha=0.5)
        k += 1
    """
    ax2.set_xlabel('minutos')
    ax2.set_xlim3d(0, hours[-1])
    ax2.set_ylabel('dia')
    ax2.set_ylim3d(0, days[-1])
    ax2.set_zlabel('Dir')
    ax2.set_zlim3d(0, 360)
    plt.show()
コード例 #13
0
def funDisplayDifferenceCurveIn3D(vecDigitLevel, inputData_x, dataToDisplay_y, xLabelText, yLabelText, zLabelText, titleText, figureName):
    '''
    Exactly the same as the function above, but in 3D, yes in 3D, it is the future here.
    '''
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.2)

    xs = inputData_x
    verts = []
    tabColor = []
    zs = vecDigitLevel
    for ii in np.arange(0,np.size(vecDigitLevel)):
        ys = dataToDisplay_y[ii,:]    
        ys[0], ys[-1] = 0, 0  
        verts.append(list(zip(xs, ys)))
        tabColor.append(list(cc(repr(vecDigitLevel[ii]/255.))))

    poly = PolyCollection(verts, facecolors = tabColor)
    poly.set_alpha(0.7)

    ax.add_collection3d(poly, zs=zs, zdir='y')
    ax.set_xlabel(xLabelText)#'level search')
    ax.set_xlim3d(0, 255)
    ax.set_ylabel(yLabelText)#'level tested')
    ax.set_ylim3d(-1, 256)
    ax.set_zlabel(zLabelText)#L difference')
    ax.set_zlim3d(0, 1)
    plt.title(titleText)#'Various difference curves in 3D')
    plt.draw()
    plt.savefig(figureName)# dirToSaveResults+prefixName+'_c1_2.png')
コード例 #14
0
ファイル: a_Plotter.py プロジェクト: priyanka27s/TA_software
 def set_data(self, zname, zdata, zcolor):
     if zdata!=None:
         if self.overall_plot_type=="polygon":
            if zname not in self.clts: #plottables['plotted']:#self.pd.list_data():
                clt=PolyCollection(zdata, alpha=0.5, antialiased=True)#, rasterized=False, antialiased=False)
                clt.set_color(colorConverter.to_rgba(zcolor))                
                self.clts[zname]=clt
                self.axe.add_collection(self.clts[zname], autolim=True)
            else:                
                self.clts[zname].set_verts(zdata)
         if self.overall_plot_type=="XY":
             if zname not in self.clts:
                 clt = LineCollection(zdata)#, offsets=offs)
                 clt.set_color(colors)
                 #print dir(clt)
                 self.clts[zname]=clt
                 self.axe.add_collection(self.clts[zname], autolim=True)
                 self.axe.autoscale_view()
             else:
                 self.clts[zname].set_segments(zdata)
         if self.overall_plot_type=="img":
             if zname not in self.clts:
                 axeimg=self.axe.imshow( Magvec, 
                                        vmin=amin(Magvec),
                                        vmax=0.001, #amax(Magvec), 
                                        aspect="auto", origin="lower",
                                 extent=[amin(yoko),amax(yoko), amin(freq),amax(freq)],
                                 #cmap='RdBu'
                                 )
                 self.fig.colorbar(axeimg)
コード例 #15
0
ファイル: plotting.py プロジェクト: r1k/py_libr1k
def plot_3dfreq_sweep_error(error, ampl):
    
    from mpl_toolkits.mplot3d import axes3d, Axes3D
    import matplotlib.pyplot as plt
    from matplotlib.collections import PolyCollection
    from matplotlib.colors import colorConverter
    import numpy as np
    
    cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6)
    
    
    fig = plt.figure()
    ax = Axes3D(fig)
  
    
    ax.add_collection3d(PolyCollection(error))
    
#    ax.set_xlabel('X')
    ax.set_xlim3d(0, 20000)
#    ax.set_ylabel('Y')
#    ax.set_ylim3d(-1, 4)
#    ax.set_zlabel('Z')
#    ax.set_zlim3d(0, 1)

    plt.show()
    
   
    return
コード例 #16
0
ファイル: 495_wav3.py プロジェクト: baallezx/dsp
def make_image(x):
	''' x wil be a matrix data structure. '''
	fig = plt.figure()
	ax = fig.gca(projection='3d')
#
	cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6)
#
	xs = np.arange(0, 10, 0.4)
	verts = x.get_verts('freq')
	for i in xrange(17):
		print verts[0][i],'\n'
	for i in xrange(17):
		print verts[1][i],'\n'
	zs = [0.0, 1.0, 2.0, 3.0]
#	for z in zs:
#		ys = np.random.rand(len(xs))
#		ys[0], ys[-1] = 0, 0
#		verts.append(list(zip(xs, ys)))
#	poly = PolyCollection(verts, facecolors = [cc('r'), cc('g'), cc('b'),cc('y')])
	poly = PolyCollection(verts)
	poly.set_alpha(0.3)
#	ax.add_collection3d(poly, zs=zs, zdir='y')
	ax.add_collection3d(poly, zs=zs, zdir='y')
#
	ax.set_xlabel('X')
	ax.set_xlim3d(0, 123456)
	ax.set_ylabel('Y')
	ax.set_ylim3d(0, 65536)
	ax.set_zlabel('Z')
	ax.set_zlim3d(0, 1000)
#
	plt.show()
コード例 #17
0
ファイル: mplutils.py プロジェクト: Peque/vispy
def color_to_hex(color):
    """Convert matplotlib color code to hex color code"""
    if color is None or colorConverter.to_rgba(color)[3] == 0:
        return 'none'
    else:
        rgb = colorConverter.to_rgb(color)
        return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
コード例 #18
0
ファイル: testPloys3D.py プロジェクト: dtbinh/Sniffer2
    def test_something(self):
        fig = plt.figure()
        ax = fig.gca(projection='3d')

        cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6)

        xs = np.arange(0, 10, 0.4)
        verts = []
        zs = [0.0, 1.0, 2.0, 3.0]
        for z in zs:
            ys = np.random.rand(len(xs))
            ys[0], ys[-1] = 0, 0
            verts.append(list(zip(xs, ys)))

        poly = PolyCollection(verts, facecolors = [cc('r'), cc('g'), cc('b'),
                                                   cc('y')])
        poly.set_alpha(0.7)
        ax.add_collection3d(poly, zs=zs, zdir='y')

        ax.set_xlabel('Coordinate')
        ax.set_xlim3d(0, 10)
        ax.set_ylabel('hypothesis#')
        ax.set_ylim3d(-1, 4)
        ax.set_zlabel('Concentration')
        ax.set_zlim3d(0, 1)

        plt.show()
コード例 #19
0
ファイル: test_examples.py プロジェクト: tkf/fillplots
 def test_switching_region_color(self):
     from matplotlib.colors import colorConverter
     from numpy.testing import assert_almost_equal
     self.run_example('switching_region_color.py')
     actual_colors = mapcall('get_facecolor', self.ax.collections)
     desired_colors = [[colorConverter.to_rgba('gray')]] * 3
     assert_almost_equal(actual_colors, desired_colors)
コード例 #20
0
ファイル: TimMLgui.py プロジェクト: kmcoulib/timml
def doTracelines(xstart,ystart,zstart,step,tmax,Nmax):
    global ActiveAxis, ActiveCanvas, ActiveTimmlModel, ActiveSettings
    setActiveWindow()
    win = getActiveWindow()
    ActiveAxis.set_autoscale_on(False)
    width = 0.5
    color = []
    for j in range(getActiveNumberLayers()):
        color.append( ActiveSettings.get_color('Trace',j) )
        color[j] = colorConverter.to_rgba( color[j] )
    for i in range( len(xstart) ):
        xyz, time, reason, pylayers = ActiveTimmlModel.\
            traceline(xstart[i],ystart[i],zstart[i],step,tmax,Nmax,tstart=0.0,window=win,labfrac = 2.0, Hfrac = 2.0)
        trace_color = []
        for j in range(len(xyz)-1):  # Number of segments one less than number of points
            trace_color.append( color[ pylayers[j] ] )
        points = zip( xyz[:,0], xyz[:,1] )
        segments = zip( points[:-1], points[1:] )
        LC = LineCollection(segments, colors = trace_color)
        LC.set_linewidth(width)
        ActiveAxis.add_collection(LC)
        #ActiveAxis.plot( xyz[:,0], xyz[:,1], 'b' )
    ActiveAxis.set_xlim(win[0],win[2])
    ActiveAxis.set_ylim(win[1],win[3])
    ActiveCanvas.draw()
コード例 #21
0
def plot_weights(weights_list, title="Neurons weights progress", y_lim = None):

    # Plot
    # Make a list of colors cycling through the rgbcmyk series.
    colors = [colorConverter.to_rgba(c) for c in ('k', 'r', 'g', 'b', 'c', 'y', 'm')]

    axes = plt.axes()
    ax4 = axes # unpack the axes

    ncurves = 1
    offs = (0.0, 0.0)

    segs = []
    for i in range(ncurves):
        curve = weights_list
        segs.append(curve)

    col = collections.LineCollection(segs, offsets=offs)
    ax4.add_collection(col, autolim=True)
    col.set_color(colors)
    ax4.autoscale_view()
    ax4.set_title(title)
    ax4.set_xlabel('Time ms')
    ax4.set_ylabel('Weight pA')
    if y_lim :
        ax4.set_ylim(0, y_lim)

    plt.show()
コード例 #22
0
ファイル: axes3d.py プロジェクト: gkliska/razvoj
def test_polys():
    from matplotlib.collections import LineCollection, PolyCollection
    from matplotlib.colors import colorConverter

    cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6)

    ax = Axes3D()
    xs = npy.arange(0,10,0.4)
    verts = []
    zs = [0.0,1.0,2.0,3.0]
    for z in zs:
        ys = [random.random() for x in xs]
        ys[0],ys[-1] = 0,0
        verts.append(zip(xs,ys))

    poly = PolyCollection(verts, facecolors = [cc('r'),cc('g'),cc('b'),
                                               cc('y')])
    #patches = art3d.Poly3DCollectionW(poly, zs=zs, dir='y')
    #poly = PolyCollection(verts)
    ax.add_collection(poly,zs=zs,dir='y')
    #ax.wrapped.add_collection(poly)
    #
    ax.plot(xs,ys, z=z, dir='y', c='r')
    ax.set_xlim(0,10)
    ax.set_ylim(-1,4)
    ax.set_zlim(0,1)
コード例 #23
0
ファイル: plotutil.py プロジェクト: richardsheridan/bumps
def dhsv(color, dh=0., ds=0., dv=0., da=0.):
    """
    Modify color on hsv scale.

    *dv* change intensity, e.g., +0.1 to brighten, -0.1 to darken.
    *dh* change hue
    *ds* change saturation
    *da* change transparency

    Color can be any valid matplotlib color.  The hsv scale is [0,1] in
    each dimension.  Saturation, value and alpha scales are clipped to [0,1]
    after changing.  The hue scale wraps between red to violet.

    :Example:

    Make sea green 10% darker:

        >>> from bumps.plotutil import dhsv
        >>> darker = dhsv('seagreen', dv=-0.1)
        >>> print([int(v*255) for v in darker])
        [37, 113, 71, 255]
    """
    from matplotlib.colors import colorConverter
    from colorsys import rgb_to_hsv, hsv_to_rgb
    from numpy import clip, array, fmod
    r, g, b, a = colorConverter.to_rgba(color)
    # print "from color",r,g,b,a
    h, s, v = rgb_to_hsv(r, g, b)
    s, v, a = [clip(val, 0., 1.) for val in (s + ds, v + dv, a + da)]
    h = fmod(h + dh, 1.)
    r, g, b = hsv_to_rgb(h, s, v)
    # print "to color",r,g,b,a
    return array((r, g, b, a))
コード例 #24
0
ファイル: _visual.py プロジェクト: ilogue/expyfun
def _convert_color(color, byte=True):
    """Convert 3- or 4-element color into OpenGL usable color"""
    color = (0., 0., 0., 0.) if color is None else color
    color = 255 * np.array(colorConverter.to_rgba(color))
    color = color.astype(np.uint8)
    if not byte:
        color = (color / 255.).astype(np.float32)
    return tuple(color)
コード例 #25
0
def polygon3D(verts, axes, color='b', alpha=0.6):
	x = [verts[i][0] for i in xrange(len(verts))]
	y = [verts[i][1] for i in xrange(len(verts))]
	z = [verts[i][2] for i in xrange(len(verts))]
	poly = Poly3DCollection(
		[zip(x, y, z)], 
		facecolor=[colorConverter.to_rgba(color, alpha)])
	axes.add_collection3d(poly)
コード例 #26
0
 def set_data(self, zname, zdata, zcolor):
     if zdata!=None:
        if zname not in self.clts: #plottables['plotted']:#self.pd.list_data():
            clt=PolyCollection(zdata, alpha=0.5, antialiased=True)#, rasterized=False, antialiased=False)
            clt.set_color(colorConverter.to_rgba(zcolor))                
            self.clts[zname]=clt
            self.axe.add_collection(self.clts[zname], autolim=True)
        else:                
            self.clts[zname].set_verts(zdata)
コード例 #27
0
    def bar3d(self, x, y, z, dx, dy, dz, color='b'):
        '''
        Generate a 3D bar, or multiple bars.

        When generating multiple bars, x, y, z have to be arrays.
        dx, dy, dz can still be scalars.
        '''

        had_data = self.has_data()

        if not cbook.iterable(x):
            x, y, z = [x], [y], [z]
        if not cbook.iterable(dx):
            dx, dy, dz = [dx], [dy], [dz]
        if len(dx) == 1:
            dx = dx * len(x)
            dy = dy * len(x)
            dz = dz * len(x)

        minx, miny, minz = 1e20, 1e20, 1e20
        maxx, maxy, maxz = -1e20, -1e20, -1e20

        polys = []
        for xi, yi, zi, dxi, dyi, dzi in zip(x, y, z, dx, dy, dz):
            minx = min(xi, minx)
            maxx = max(xi + dxi, maxx)
            miny = min(yi, miny)
            maxy = max(yi + dyi, maxy)
            minz = min(zi, minz)
            maxz = max(zi + dzi, maxz)

            polys.extend([
                ((xi, yi, zi), (xi + dxi, yi, zi),
                    (xi + dxi, yi + dyi, zi), (xi, yi + dyi, zi)),
                ((xi, yi, zi + dzi), (xi + dxi, yi, zi + dzi),
                    (xi + dxi, yi + dyi, zi + dzi), (xi, yi + dyi, zi + dzi)),

                ((xi, yi, zi), (xi + dxi, yi, zi),
                    (xi + dxi, yi, zi + dzi), (xi, yi, zi + dzi)),
                ((xi, yi + dyi, zi), (xi + dxi, yi + dyi, zi),
                    (xi + dxi, yi + dyi, zi + dzi), (xi, yi + dyi, zi + dzi)),

                ((xi, yi, zi), (xi, yi + dyi, zi),
                    (xi, yi + dyi, zi + dzi), (xi, yi, zi + dzi)),
                ((xi + dxi, yi, zi), (xi + dxi, yi + dyi, zi),
                    (xi + dxi, yi + dyi, zi + dzi), (xi + dxi, yi, zi + dzi)),
            ])

        color = np.array(colorConverter.to_rgba(color))
        normals = self._generate_normals(polys)
        colors = self._shade_colors(color, normals)

        col = art3d.Poly3DCollection(polys, facecolor=colors)
        self.add_collection(col)

        self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data)
コード例 #28
0
def draw3DCube(cube, axes, color):
	r1 = 0.85
	r3 = 0.8
	a1 = 0.9
	a2 = 0.8

	if isinstance(cube, CH.Cube):
		if cube.dim == 0:
			points = map(lambda x:x[0], cube.intervals)
			print cube
			raw_input('>>')
			x, y, z = map(np.array, zip(*points))
			axes.scatter(y, z, -x, c=color, marker='o')
		elif cube.dim == 1:
			points = list(product(*map(set, cube.intervals)))
			V = [homothetic(cube.center, r1, P) for P in points]
			x, y, z = map(np.array, zip(*V))
			axes.plot(y, z, -x, color, linewidth=2, )
		elif cube.dim == 2:
			points = list(product(*map(set, cube.intervals)))
			V = [homothetic(cube.center, r1, P) for P in points]
			x, y, z = map(np.array, zip(*V))
			X, Y, Z = map(lambda x: x.copy(), [x, y, z])
			X[2], X[3] = x[3], x[2]
			Y[2], Y[3] = y[3], y[2]
			Z[2], Z[3] = z[3], z[2]
			poly = Poly3DCollection(
				[zip(Y, Z, -X)], 
				facecolor=colorConverter.to_rgba(color, a2))
			axes.add_collection3d(poly)
		elif cube.dim == 3:
			for face in cube.border():
				points = list(product(*map(set, face.intervals)))
				V = [homothetic(cube.center, r3, P) for P in points]
				x, y, z = map(np.array, zip(*V))
				X, Y, Z = map(lambda x: x.copy(), [x, y, z])
				X[2], X[3] = x[3], x[2]
				Y[2], Y[3] = y[3], y[2]
				Z[2], Z[3] = z[3], z[2]
				poly = Poly3DCollection(
					[zip(Y, Z, -X)], 
					facecolor=colorConverter.to_rgba(color, 1))
				axes.add_collection3d(poly)
コード例 #29
0
ファイル: show_domains.py プロジェクト: regulomics/sherpa
def colored_with_affinity(arr, domains, affinity=False, chr=None, cc=None):
  arr = np.ma.fix_invalid(arr)
  # PuBu
  colored = cm.jet(pltcol.LogNorm()(arr))
  normalizer = Normalize(vmin=-1, vmax=3)
  non_empty_domains = remove_empty_domains(arr, topify(domains))
  if affinity:
    doms_affinity = domains_affinity(arr, non_empty_domains)
    heatmap_notlog(np.clip(doms_affinity, 0, 10))
    doms_affinity_log = np.log(doms_affinity)
    affinity_thr = np.nanmean(doms_affinity_log) + np.nanstd(doms_affinity_log)
    affinity_thr = np.exp(affinity_thr)
    affinity_thr = np.nanmean(doms_affinity) + 1 * np.nanstd(doms_affinity)
    affinity_normalizer = Normalize(vmin=affinity_thr, vmax=10)

  for i, dom in enumerate(domains):
    begin, end = dom.get_begin(), dom.get_end()
    if end - begin < DOM_THR:
      continue
    color = dom.color or BORDER_COLOR
    try:
      color_num = int(dom.color)
      if color_num >=0 :
        color = COLOR_LIST[color_num]
      else:
        color = COLORS['0']
    except:
      pass
    if cc:
      color = COLORS[cc.get((chr, dom.color), '0')]
    color = colorConverter.to_rgba(color)
    for i in range(begin, end + 1):
      if i != end:
        colored[i, end] = color
      if i != begin:
        colored[begin, i] = color
    #colored[begin, begin] = colorConverter.to_rgba('black')
    #colored[end, end] = colorConverter.to_rgba('black')
  if affinity:
    for i, dom in enumerate(non_empty_domains):
      begin, end = dom.get_begin(), dom.get_end()
      for j, dom2 in enumerate(non_empty_domains):
        if j <= i:
          continue
        begin2, end2 = dom2.get_begin(), dom2.get_end()
        if doms_affinity[i, j] < affinity_thr:
          continue
        color = cm.gnuplot(affinity_normalizer(doms_affinity[i, j]))
        for k in range(begin, end + 1):
          colored[k, begin2] = color
          colored[k, end2] = color
        for k in range(begin2, end2 + 1):
          colored[begin, k] = color
          colored[end, k] = color
  return colored
コード例 #30
0
def mpl_to_css_color(color, alpha=None, isRGB=True):
    """Convert Matplotlib color spec (or rgb tuple + alpha) to CSS color string."""
    if not isRGB:
        r, g, b, alpha = colorConverter.to_rgba(color)
        color = (r, g, b)
    if alpha is None and len(color) == 4:
        alpha = color[3]
    if alpha is None:
        return rgb2hex(color[:3])
    else:
        return 'rgba(%d, %d, %d, %.3g)' % (color[0] * 255, color[1] * 255, color[2] * 255, alpha)
コード例 #31
0
ファイル: fatband.py プロジェクト: CaiCheng-sicnu/pyprocar
def plot_band_weight(kslist,
                     ekslist,
                     wkslist=None,
                     efermi=None,
                     shift_efermi=False,
                     yrange=None,
                     output=None,
                     style='alpha',
                     color='blue',
                     axis=None,
                     width=10,
                     fatness=4,
                     xticks=None,
                     cmap=mpl.cm.bwr,
                     weight_min=-0.1,
                     weight_max=0.6):
    if axis is None:
        fig, a = plt.subplots()
    else:
        a = axis
    if efermi is not None and shift_efermi:
        ekslist = np.array(ekslist) - efermi
    else:
        ekslist = np.array(ekslist)

    xmax = max(kslist[0])
    if yrange is None:
        yrange = (np.array(ekslist).flatten().min() - 0.66,
                  np.array(ekslist).flatten().max() + 0.66)
    if wkslist is not None:
        for i in range(len(kslist)):
            x = kslist[i]
            y = ekslist[i]
            #lwidths=np.ones(len(x))
            points = np.array([x, y]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            if style == 'width':
                lwidths = np.array(wkslist[i]) * width
                lc = LineCollection(segments, linewidths=lwidths, colors=color)
            elif style == 'alpha':
                lwidths = np.array(wkslist[i]) * width

                # The alpha values sometimes goes above 1 so in those cases we will normalize
                # the alpha values. -Uthpala  
                alpha_values = [lwidth / (width + 0.05) for lwidth in lwidths]
                if max(alpha_values) > 1:
                    print('alpha is larger than 1. Renormalizing values.')
                    alpha_values = [alpha_i / max(alpha_values) for alpha_i in alpha_values]

                lc = LineCollection(
                    segments,
                    linewidths=[fatness] * len(x),
                    colors=[colorConverter.to_rgba(color, alpha=alpha_i) for alpha_i in alpha_values])

            elif style == 'color' or style == 'colormap':
                lwidths = np.array(wkslist[i]) * width
                norm = mpl.colors.Normalize(vmin=weight_min, vmax=weight_max)
                #norm = mpl.colors.SymLogNorm(linthresh=0.03,vmin=weight_min, vmax=weight_max)
                m = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
                #lc = LineCollection(segments,linewidths=np.abs(norm(lwidths)-0.5)*1, colors=[m.to_rgba(lwidth) for lwidth in lwidths])
                lc = LineCollection(
                    segments,
                    linewidths=lwidths,
                    colors=[m.to_rgba(lwidth) for lwidth in lwidths])
            a.add_collection(lc)
    if axis is None:
        for ks, eks in zip(kslist, ekslist):
            a.plot(ks, eks, color='gray', linewidth=0.01)
        #a.set_xlim(0, xmax)
        #a.set_ylim(yrange)
        if xticks is not None:
            a.set_xticks(xticks[1])
            a.set_xticklabels(xticks[0])
            for x in xticks[1]:
                a.axvline(x, alpha=0.6, color='black', linewidth=0.7)
        if efermi is not None:
            if shift_efermi:
                a.axhline(linestyle='--', color='black')
            else:
                a.axhline(efermi, linestyle='--', color='black')

    return a
コード例 #32
0
def draw_networkx_edges(G, pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=None,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None,
                        ax=None,
                        arrows=True,
                        label=None,
                        **kwds):
    """Draw the edges of the graph G.

    This draws only the edges of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       If not specified a spring layout positioning will be computed.
       See networkx.layout for functions that compute node positions.

    edgelist : collection of edge tuples
       Draw only specified edges(default=G.edges())

    width : float
       Line width of edges (default =1.0)

    edge_color : color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    style : string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)

    alpha : float
       The edge transparency (default=1.0)

    edge_ cmap : Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)

    edge_vmin,edge_vmax : floats
       Minimum and maximum for edge colormap scaling (default=None)

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.

    label : [None| string]
       Label for legend

    Notes
    -----
    For directed graphs, "arrows" (actually just thicker stubs) are drawn
    at the head end.  Arrows can be turned off with keyword arrows=False.
    Yes, it is ugly but drawing proper arrows with Matplotlib this
    way is tricky.

    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G))

    Also see the NetworkX drawing examples at
    http://networkx.lanl.gov/gallery.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib
        import matplotlib.pylab as pylab
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter,Colormap
        from matplotlib.collections import LineCollection
        import numpy
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax=pylab.gca()

    if edgelist is None:
        edgelist=G.edges()

    if not edgelist or len(edgelist)==0: # no edges!
        return None

    # set edge positions
    edge_pos=numpy.asarray([(pos[e[0]],pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width,)
    else:
        lw = width

    if not cb.is_string_like(edge_color) \
           and cb.iterable(edge_color) \
           and len(edge_color)==len(edge_pos):
        if numpy.alltrue([cb.is_string_like(c)
                         for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple([colorConverter.to_rgba(c,alpha)
                                 for c in edge_color])
        elif numpy.alltrue([not cb.is_string_like(c)
                           for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if numpy.alltrue([cb.iterable(c) and len(c) in (3,4)
                             for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError('edge_color must consist of either color names or numbers')
    else:
        if cb.is_string_like(edge_color) or len(edge_color)==1:
            edge_colors = ( colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')

    edge_collection = LineCollection(edge_pos,
                                     colors       = edge_colors,
                                     linewidths   = lw,
                                     antialiaseds = (1,),
                                     linestyle    = style,
                                     transOffset = ax.transData,
                                     )


    edge_collection.set_zorder(1) # edges go behind nodes
    edge_collection.set_label(label)
    ax.add_collection(edge_collection)

    # Note: there was a bug in mpl regarding the handling of alpha values for
    # each line in a LineCollection.  It was fixed in matplotlib in r7184 and
    # r7189 (June 6 2009).  We should then not set the alpha value globally,
    # since the user can instead provide per-edge alphas now.  Only set it
    # globally if provided as a scalar.
    if cb.is_numlike(alpha):
        edge_collection.set_alpha(alpha)

    if edge_colors is None:
        if edge_cmap is not None:
            assert(isinstance(edge_cmap, Colormap))
        edge_collection.set_array(numpy.asarray(edge_color))
        edge_collection.set_cmap(edge_cmap)
        if edge_vmin is not None or edge_vmax is not None:
            edge_collection.set_clim(edge_vmin, edge_vmax)
        else:
            edge_collection.autoscale()
        pylab.sci(edge_collection)

    arrow_collection=None

    if G.is_directed() and arrows:

        # a directed graph hack
        # draw thick line segments at head end of edge
        # waiting for someone else to implement arrows that will work
        arrow_colors = edge_colors
        a_pos=[]
        p=1.0-0.25 # make head segment 25 percent of edge length
        for src,dst in edge_pos:
            x1,y1=src
            x2,y2=dst
            dx=x2-x1 # x offset
            dy=y2-y1 # y offset
            d=numpy.sqrt(float(dx**2+dy**2)) # length of edge
            if d==0: # source and target at same position
                continue
            if dx==0: # vertical edge
                xa=x2
                ya=dy*p+y1
            if dy==0: # horizontal edge
                ya=y2
                xa=dx*p+x1
            else:
                theta=numpy.arctan2(dy,dx)
                xa=p*d*numpy.cos(theta)+x1
                ya=p*d*numpy.sin(theta)+y1

            a_pos.append(((xa,ya),(x2,y2)))

        arrow_collection = LineCollection(a_pos,
                                colors       = arrow_colors,
                                linewidths   = [4*ww for ww in lw],
                                antialiaseds = (1,),
                                transOffset = ax.transData,
                                )

        arrow_collection.set_zorder(1) # edges go behind nodes
        arrow_collection.set_label(label)
        ax.add_collection(arrow_collection)


    # update view
    minx = numpy.amin(numpy.ravel(edge_pos[:,:,0]))
    maxx = numpy.amax(numpy.ravel(edge_pos[:,:,0]))
    miny = numpy.amin(numpy.ravel(edge_pos[:,:,1]))
    maxy = numpy.amax(numpy.ravel(edge_pos[:,:,1]))

    w = maxx-minx
    h = maxy-miny
    padx, pady = 0.05*w, 0.05*h
    corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
    ax.update_datalim( corners)
    ax.autoscale_view()

#    if arrow_collection:

    return edge_collection
コード例 #33
0
 def set_bad(self, color='k', alpha=None):
     """Set color to be used for masked values.
     """
     self._rgba_bad = colorConverter.to_rgba(color, alpha)
コード例 #34
0
    def draw_roll(self):


        roll = self.get_roll()

        # build and set fig obj
        plt.ioff()
        fig = plt.figure(figsize=(4, 3))
        a1 = fig.add_subplot(111)
        a1.axis("equal")
        a1.set_facecolor("black")

        # change unit of time axis from tick to second
        tick = self.get_total_ticks()
        second = mido.tick2second(tick, self.ticks_per_beat, self.get_tempo())
        #print(second)
        if second > 10:
            x_label_period_sec = second // 10
        else:
            x_label_period_sec = second / 10  # ms
        #print(x_label_period_sec)
        x_label_interval = mido.second2tick(x_label_period_sec, self.ticks_per_beat, self.get_tempo()) / self.sr
        #print(x_label_interval)
        plt.xticks([int(x * x_label_interval) for x in range(20)], [round(x * x_label_period_sec, 2) for x in range(20)])

        # change scale and label of y axis
        plt.yticks([y*16 for y in range(8)], [y*16 for y in range(8)])

        # build colors
        channel_nb = 16
        transparent = colorConverter.to_rgba('black')
        colors = [mpl.colors.to_rgba(mpl.colors.hsv_to_rgb((i / channel_nb, 1, 1)), alpha=1) for i in range(channel_nb)]
        cmaps = [mpl.colors.LinearSegmentedColormap.from_list('my_cmap', [transparent, colors[i]], 128) for i in
                 range(channel_nb)]

        # build color maps
        for i in range(channel_nb):
            cmaps[i]._init()
            # create your alpha array and fill the colormap with them.
            alphas = np.linspace(0, 1, cmaps[i].N + 3)
            # create the _lut array, with rgba values
            cmaps[i]._lut[:, -1] = alphas


        # draw piano roll and stack image on a1
        for i in range(channel_nb):
            try:
                a1.imshow(roll[i], origin="lower", interpolation='nearest', cmap=cmaps[i], aspect='auto')
            except IndexError:
                pass

        # draw color bar

        colors = [mpl.colors.hsv_to_rgb((i / channel_nb, 1, 1)) for i in range(channel_nb)]
        cmap = mpl.colors.LinearSegmentedColormap.from_list('my_cmap', colors, 16)
        a2 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
        cbar = mpl.colorbar.ColorbarBase(a2, cmap=cmap,
                                        orientation='horizontal',
                                        ticks=list(range(16)))

        # show piano roll
        plt.draw()
        plt.ion()
        plt.show(block=True)
コード例 #35
0
def dd(arg):
    return colorConverter.to_rgba(arg, alpha=0.1)
コード例 #36
0
def draw_edges(G,
               pos,
               ax,
               edgelist=None,
               width=1.0,
               width_adjuster=50,
               edge_color='k',
               style='solid',
               alpha=None,
               edge_cmap=None,
               edge_vmin=None,
               edge_vmax=None,
               traversal_weight=1.0,
               edge_delengthify=0.15,
               arrows=True,
               label=None,
               zorder=1,
               **kwds):
    """
    Code cleaned-up version of networkx.draw_networkx_edges

    New args:

    width_adjuster - the line width is generated from the weight if present, use this adjuster to thicken the lines (multiply)
    """
    if edgelist is None:
        edgelist = G.edges()

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    # set edge positions
    edge_pos = [(pos[e[0]], pos[e[1]]) for e in edgelist]
    new_ep = []
    for e in edge_pos:
        x, y = e[0]
        dx, dy = e[1]

        # Get edge length
        elx = (dx - x) * edge_delengthify
        ely = (dy - y) * edge_delengthify

        x += elx
        y += ely
        dx -= elx
        dy -= ely

        new_ep.append(((x, y), (dx, dy)))
    edge_pos = numpy.asarray(new_ep)

    if not cb.iterable(width):
        #print [G.get_edge_data(n[0], n[1])['weight'] for n in edgelist]
        # see if I can find an edge attribute:
        if 'weight' in G.get_edge_data(edgelist[0][0],
                                       edgelist[0][1]):  # Test an edge
            lw = [
                0.5 +
                ((G.get_edge_data(n[0], n[1])['weight'] - traversal_weight) *
                 width_adjuster) for n in edgelist
            ]
        else:
            lw = (width, )
    else:
        lw = width

    if not is_string_like(edge_color) and cb.iterable(edge_color) and len(
            edge_color) == len(edge_pos):
        if numpy.alltrue([cb.is_string_like(c) for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple(
                [colorConverter.to_rgba(c, alpha) for c in edge_color])
        elif numpy.alltrue([not cb.is_string_like(c) for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if numpy.alltrue(
                [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError(
                'edge_color must consist of either color names or numbers')
    else:
        if is_string_like(edge_color) or len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError(
                'edge_color must be a single color or list of exactly m colors where m is the number or edges'
            )

    edge_collection = LineCollection(edge_pos,
                                     colors=edge_colors,
                                     linewidths=lw,
                                     antialiaseds=(1, ),
                                     linestyle=style,
                                     transOffset=ax.transData,
                                     zorder=zorder)

    edge_collection.set_label(label)
    ax.add_collection(edge_collection)

    if cb.is_numlike(alpha):
        edge_collection.set_alpha(alpha)

    if edge_colors is None:
        if edge_cmap is not None:
            assert (isinstance(edge_cmap, Colormap))
        edge_collection.set_array(numpy.asarray(edge_color))
        edge_collection.set_cmap(edge_cmap)
        if edge_vmin is not None or edge_vmax is not None:
            edge_collection.set_clim(edge_vmin, edge_vmax)
        else:
            edge_collection.autoscale()

    # update view
    '''
    minx = numpy.amin(numpy.ravel(edge_pos[:,:,0]))
    maxx = numpy.amax(numpy.ravel(edge_pos[:,:,0]))
    miny = numpy.amin(numpy.ravel(edge_pos[:,:,1]))
    maxy = numpy.amax(numpy.ravel(edge_pos[:,:,1]))

    w = maxx-minx
    h = maxy-miny
    padx,  pady = 0.05*w, 0.05*h
    corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
    ax.update_datalim(corners)
    ax.autoscale_view()
    '''
    return (edge_collection)
コード例 #37
0
#------------------------------------------------------------------------------
# Set up string variables for the input files/data
#------------------------------------------------------------------------------

startFilename = "point_stat_"
midFilename = "0000L_"
endFilename = "0000V_cts.txt"
#inputRootDir = "/discover/nobackup/projects/nu-wrf/members/bvanaart/SkillScoreRuns/MET_output/PointStat/round"
#exptDirList = ["0_default","2_bl_pbl_1_sf_sfclay_11","2_bl_pbl_2_sf_sfclay_2","3_ra_lw_phys_4_sw_phys_4","3_ra_lw_phys_56_sw_phys_56","4_moist_adv_opt_2","4_moist_adv_opt_4"]
exptDirList = nuwrfRunDirs

#exptLabels = [" Def_Goddard4"," YSU PBL, MM5 M-O SL", " MYJ TKE PBL, M-O-J SL", " RRTMG"," 2014 Goddard rad"," Monotonic advec"," 5th-order WENO advec"]
exptLabels = nuwrfRunLabels
myColors = [
    colorConverter.to_rgba(c)
    for c in ('red', 'black', 'goldenrod', 'blue', 'darkseagreen', 'darkgreen',
              'mediumpurple', 'indigo', 'darkturquoise')
]
numExpts = len(exptLabels)

#Set output PDF file name, which will host several plots
eLabel = '-'.join(str(x) for x in exptLabels[0:2])
pdfName = 'T-Q-U-V_SkillScores_' + ''.join(eLabel.split()) + '.pdf'
pp = PdfPages(pdfName)

#------------------------------------------------------------------------------
# Find total # of time-periods to plot
#------------------------------------------------------------------------------

startDate = datetime.datetime(int(beginYear), int(beginMon), int(beginDate),
コード例 #38
0
def makeGrey(col_list):
    return [
        colorConverter.to_rgba("#cccccc", 0.1) for i in range(len(col_list))
    ]
コード例 #39
0
    # print "itercategories:"
    # print itercategories(dict(yaxis.items() + singletons.items()))
    # print "others:"
    # print singletons
    if options.verbose:
        sep = ","
        print sep.join(metadata)
        for tup in formatted_data:
            print sep.join(map(str, tup))

    # Produce Speedup Graph
    N = len(column(formatted_data,0))
    ind = np.arange(N) + 0.15  # the x locations for the groups
    width = (0.7/len(metadata[1:]))       # the width of the bars
    #old_colors = map(lambda c: colorConverter.to_rgba(c, 0.5), ["#00C12B", "#133AAC", "#FFAE00", "#FF1800", "#24913C", "#062170", "#A67100", "#A61000"])
    colors = map(lambda c: colorConverter.to_rgba(c, 0.5), ["#0000DD", "#FF8800",  "#24913C", "#062170", "#123456", "#654321"])
    xlabel_offset = 0
    xbar_offset = 0
    xbar_space = 0.05

    bars = []
    names = []
    legend_colors = []

    fig, ax = plt.subplots()

    if options.logscale:
        ax.set_yscale("log", basey=options.logscale, nonposy="clip")
    ax.get_yaxis().set_major_formatter(ScalarFormatter())

    for i in range(1,len(formatted_data[0])):
コード例 #40
0
    def add_label(self,
                  label,
                  color=None,
                  alpha=1,
                  scalar_thresh=None,
                  borders=False,
                  hemi=None,
                  subdir=None):
        """Add an ROI label to the image.

        Parameters
        ----------
        label : str | instance of Label
            label filepath or name. Can also be an instance of
            an object with attributes "hemi", "vertices", "name", and
            optionally "color" and "values" (if scalar_thresh is not None).
        color : matplotlib-style color | None
            anything matplotlib accepts: string, RGB, hex, etc. (default
            "crimson")
        alpha : float in [0, 1]
            alpha level to control opacity
        scalar_thresh : None or number
            threshold the label ids using this value in the label
            file's scalar field (i.e. label only vertices with
            scalar >= thresh)
        borders : bool | int
            Show only label borders. If int, specify the number of steps
            (away from the true border) along the cortical mesh to include
            as part of the border definition.
        hemi : str | None
            If None, it is assumed to belong to the hemipshere being
            shown.
        subdir : None | str
            If a label is specified as name, subdir can be used to indicate
            that the label file is in a sub-directory of the subject's
            label directory rather than in the label directory itself (e.g.
            for ``$SUBJECTS_DIR/$SUBJECT/label/aparc/lh.cuneus.label``
            ``brain.add_label('cuneus', subdir='aparc')``).

        Notes
        -----
        To remove previously added labels, run Brain.remove_labels().
        """
        from matplotlib.colors import colorConverter
        if isinstance(label, str):
            if color is None:
                color = "crimson"

            if os.path.isfile(label):
                filepath = label
                label = read_label(filepath)
                hemi = label.hemi
                label_name = os.path.basename(filepath).split('.')[1]
            else:
                hemi = self._check_hemi(hemi)
                label_name = label
                label_fname = ".".join([hemi, label_name, 'label'])
                if subdir is None:
                    filepath = pjoin(self._subjects_dir, self._subject_id,
                                     'label', label_fname)
                else:
                    filepath = pjoin(self._subjects_dir, self._subject_id,
                                     'label', subdir, label_fname)
                if not os.path.exists(filepath):
                    raise ValueError('Label file %s does not exist' % filepath)
                label = read_label(filepath)
            ids = label.vertices
            scalars = label.values
        else:
            # try to extract parameters from label instance
            try:
                hemi = label.hemi
                ids = label.vertices
                if label.name is None:
                    label_name = 'unnamed'
                else:
                    label_name = str(label.name)

                if color is None:
                    if hasattr(label, 'color') and label.color is not None:
                        color = label.color
                    else:
                        color = "crimson"

                if scalar_thresh is not None:
                    scalars = label.values
            except Exception:
                raise ValueError('Label was not a filename (str), and could '
                                 'not be understood as a class. The class '
                                 'must have attributes "hemi", "vertices", '
                                 '"name", and (if scalar_thresh is not None)'
                                 '"values"')
            hemi = self._check_hemi(hemi)

        if scalar_thresh is not None:
            ids = ids[scalars >= scalar_thresh]

        # XXX: add support for label_name
        self._label_name = label_name

        label = np.zeros(self.geo[hemi].coords.shape[0])
        label[ids] = 1
        color = colorConverter.to_rgba(color, alpha)
        cmap = np.array([(
            0,
            0,
            0,
            0,
        ), color])
        ctable = np.round(cmap * 255).astype(np.uint8)

        for ri, v in enumerate(self._views):
            if self._hemi != 'split':
                ci = 0
            else:
                ci = 0 if hemi == 'lh' else 1
            views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict
            self._renderer.subplot(ri, ci)
            if borders:
                surface = {
                    'rr': self.geo[hemi].coords,
                    'tris': self.geo[hemi].faces,
                }
                self._renderer.contour(surface,
                                       label, [1.0],
                                       color=color,
                                       kind='tube')
            else:
                self._renderer.mesh(x=self.geo[hemi].coords[:, 0],
                                    y=self.geo[hemi].coords[:, 1],
                                    z=self.geo[hemi].coords[:, 2],
                                    triangles=self.geo[hemi].faces,
                                    scalars=label,
                                    color=None,
                                    colormap=ctable,
                                    backface_culling=False)
            self._renderer.set_camera(azimuth=views_dict[v].azim,
                                      elevation=views_dict[v].elev)
コード例 #41
0
xx, yy = np.meshgrid(xs1, xs2)  # create the grid
# Initialize and fill the 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] = nn_predict(xx[i,j], yy[i,j])
        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])

# Create a color map to show the classification colors of each grid point
cmap = ListedColormap([
    colorConverter.to_rgba('r', alpha=0.30),
    colorConverter.to_rgba('b', alpha=0.30)
])
# Plot the classification plane with decision boundary and input samples
plt.contourf(xx, yy, classification_plane, cmap=cmap)
plt.show()

xTrain, yTrain = generate(12, num_classes, [[3.0, 0], [3.0, 3.0], [0, 3.0]],
                          True)
yTrain = yTrain % 2
# colors = ['r' if l == 0.0 else 'b' for l in yTrain[:]]
# plt.scatter(xTrain[:,0], xTrain[:,1], c=colors)

xr = []
xb = []
for (l, k) in zip(yTrain[:], xTrain[:]):
コード例 #42
0
def _plot_morphology3D(morpho, figure, colors, values, value_norm,
                       value_colormap,
                       show_diameters=True,
                       show_compartments=False):
    import mayavi.mlab as mayavi
    if values is not None:
        # calculate color for the soma
        vmin, vmax = value_norm
        if vmin is None:
            vmin = min(values)
        if vmax is None:
            vmax = max(values)
        normed_value = (values[0] - vmin)/(vmax - vmin)
        colors = np.vstack(value_colormap([normed_value]))
    else:
        colors = np.vstack([colorConverter.to_rgba(c) for c in colors])
    flat_morpho = FlatMorphology(morpho)
    if isinstance(morpho, Soma):
        start_idx = 1
        # Plot the Soma
        mayavi.points3d(flat_morpho.x[0]/float(um),
                        flat_morpho.y[0]/float(um),
                        flat_morpho.z[0]/float(um),
                        flat_morpho.diameter[0]/float(um),
                        figure=figure, color=tuple(colors[0, :-1]),
                        resolution=16, scale_factor=1)
    else:
        start_idx = 0
    if show_compartments:
        # plot points at center of compartment
        if show_diameters:
            diameters = flat_morpho.diameter[start_idx:]/float(um)/10
        else:
            diameters = np.ones(len(flat_morpho.diameter) - start_idx)
        mayavi.points3d(flat_morpho.x[start_idx:]/float(um),
                        flat_morpho.y[start_idx:]/float(um),
                        flat_morpho.z[start_idx:]/float(um),
                        diameters,
                        figure=figure, color=(0, 0, 0),
                        resolution=16, scale_factor=1)
    # Plot all other compartments
    start_points = np.vstack([flat_morpho.start_x[start_idx:]/float(um),
                              flat_morpho.start_y[start_idx:]/float(um),
                              flat_morpho.start_z[start_idx:]/float(um)]).T
    end_points = np.vstack([flat_morpho.end_x[start_idx:]/float(um),
                            flat_morpho.end_y[start_idx:]/float(um),
                            flat_morpho.end_z[start_idx:]/float(um)]).T
    points = np.empty((2*len(start_points), 3))
    points[::2, :] = start_points
    points[1::2, :] = end_points
    # Create the points at start and end of the compartments
    if values is not None:
        scatter_values = values[start_idx:].repeat(2)
    else:
        scatter_values = flat_morpho.depth[start_idx:].repeat(2)
    src = mayavi.pipeline.scalar_scatter(points[:, 0],
                                         points[:, 1],
                                         points[:, 2],
                                         scatter_values,
                                         scale_factor=1)
    # Create the lines between compartments
    connections = []
    for start, end in zip(flat_morpho.starts[1:], flat_morpho.ends[1:]):
        # we only need the lines within the sections
        new_connections = [((idx-1)*2, (idx-1)*2 + 1)
                           for idx in range(start, end)]
        connections.extend(new_connections)
    connections = np.vstack(connections)
    src.mlab_source.dataset.lines = connections
    if show_diameters:
        radii = flat_morpho.diameter[start_idx:].repeat(2)/float(um)/2
        src.mlab_source.dataset.point_data.add_array(radii)
        src.mlab_source.dataset.point_data.get_array(1).name = 'radius'
        src.update()
    lines = mayavi.pipeline.stripper(src)
    if show_diameters:
        lines = mayavi.pipeline.set_active_attribute(lines,
                                                     point_scalars='radius')
        tubes = mayavi.pipeline.tube(lines)
        tubes.filter.vary_radius = 'vary_radius_by_absolute_scalar'
        tubes = mayavi.pipeline.set_active_attribute(tubes,
                                                 point_scalars='scalars')
    else:
        tubes = mayavi.pipeline.tube(lines, tube_radius=1)
    max_depth = max(flat_morpho.depth)
    if values is not None:
        surf = mayavi.pipeline.surface(tubes, colormap='prism', line_width=1,
                                       opacity=0.5, vmin=vmin, vmax=vmax)
        surf.module_manager.scalar_lut_manager.lut.number_of_colors = 256
        cmap = np.array(np.vstack(value_colormap(np.linspace(0., 1., num=256, endpoint=True)))*255.,
                        dtype=np.uint8)
    else:
        surf = mayavi.pipeline.surface(tubes, colormap='prism', line_width=1,
                                       opacity=0.5,
                                       vmin=0, vmax=max(flat_morpho.depth))
        surf.module_manager.scalar_lut_manager.lut.number_of_colors = max_depth + start_idx
        cmap = np.int_(np.round(255*colors[np.arange(max_depth + start_idx)%len(colors), :]))
    surf.module_manager.scalar_lut_manager.lut.table = cmap
    src.update()
    return surf
コード例 #43
0
    def __call__(self, plot):
        x0, x1 = plot.xlim
        y0, y1 = plot.ylim
        xx0, xx1 = plot._axes.get_xlim()
        yy0, yy1 = plot._axes.get_ylim()
        (dx, dy) = self.pixel_scale(plot)
        (xpix, ypix) = plot.image._A.shape
        ax = plot.data.axis
        px_index = plot.data.ds.coordinates.x_axis[ax]
        py_index = plot.data.ds.coordinates.y_axis[ax]
        DW = plot.data.ds.domain_width
        if self.periodic:
            pxs, pys = np.mgrid[-1:1:3j, -1:1:3j]
        else:
            pxs, pys = np.mgrid[0:0:1j, 0:0:1j]
        GLE, GRE, levels = [], [], []
        for block, mask in plot.data.blocks:
            GLE.append(block.LeftEdge.in_units("code_length"))
            GRE.append(block.RightEdge.in_units("code_length"))
            levels.append(block.Level)
        if len(GLE) == 0: return
        # Retain both units and registry
        GLE = YTArray(GLE, input_units=GLE[0].units)
        GRE = YTArray(GRE, input_units=GRE[0].units)
        levels = np.array(levels)
        min_level = self.min_level or 0
        max_level = self.max_level or levels.max()

        # sorts the three arrays in order of ascending level - this makes images look nicer
        new_indices = np.argsort(levels)
        levels = levels[new_indices]
        GLE = GLE[new_indices]
        GRE = GRE[new_indices]

        for px_off, py_off in zip(pxs.ravel(), pys.ravel()):
            pxo = px_off * DW[px_index]
            pyo = py_off * DW[py_index]
            left_edge_x = np.array((GLE[:, px_index] + pxo - x0) * dx) + xx0
            left_edge_y = np.array((GLE[:, py_index] + pyo - y0) * dy) + yy0
            right_edge_x = np.array((GRE[:, px_index] + pxo - x0) * dx) + xx0
            right_edge_y = np.array((GRE[:, py_index] + pyo - y0) * dy) + yy0
            xwidth = xpix * (right_edge_x - left_edge_x) / (xx1 - xx0)
            ywidth = ypix * (right_edge_y - left_edge_y) / (yy1 - yy0)
            visible = np.logical_and(
                np.logical_and(xwidth > self.min_pix, ywidth > self.min_pix),
                np.logical_and(levels >= min_level, levels <= max_level))

            # Grids can either be set by edgecolors OR a colormap.
            if self.edgecolors is not None:
                edgecolors = colorConverter.to_rgba(self.edgecolors,
                                                    alpha=self.alpha)
            else:  # use colormap if not explicity overridden by edgecolors
                if self.cmap is not None:
                    color_bounds = [0, plot.data.ds.index.max_level]
                    edgecolors = apply_colormap(
                        levels[visible] * 1.0,
                        color_bounds=color_bounds,
                        cmap_name=self.cmap)[0, :, :] * 1.0 / 255.
                    edgecolors[:, 3] = self.alpha
                else:
                    edgecolors = (0.0, 0.0, 0.0, self.alpha)

            if visible.nonzero()[0].size == 0: continue
            verts = np.array([
                (left_edge_x, left_edge_x, right_edge_x, right_edge_x),
                (left_edge_y, right_edge_y, right_edge_y, left_edge_y)
            ])
            verts = verts.transpose()[visible, :, :]
            grid_collection = matplotlib.collections.PolyCollection(
                verts,
                facecolors="none",
                edgecolors=edgecolors,
                linewidth=self.linewidth)
            plot._axes.hold(True)
            plot._axes.add_collection(grid_collection)

            if self.draw_ids:
                visible_ids = np.logical_and(
                    np.logical_and(xwidth > self.min_pix_ids,
                                   ywidth > self.min_pix_ids),
                    np.logical_and(levels >= min_level, levels <= max_level))
                active_ids = np.unique(plot.data['grid_indices'])
                for i in np.where(visible_ids)[0]:
                    plot._axes.text(left_edge_x[i] + (2 * (xx1 - xx0) / xpix),
                                    left_edge_y[i] + (2 * (yy1 - yy0) / ypix),
                                    "%d" % active_ids[i],
                                    clip_on=True)
            plot._axes.hold(False)
コード例 #44
0
def draw_embedding(G,
                   layout,
                   emb,
                   embedded_graph=None,
                   interaction_edges=None,
                   chain_color=None,
                   unused_color=(0.9, 0.9, 0.9, 1.0),
                   cmap=None,
                   show_labels=False,
                   overlapped_embedding=False,
                   **kwargs):
    """Draws an embedding onto the graph G, according to layout.

    If interaction_edges is not None, then only display the couplers in that
    list.  If embedded_graph is not None, the only display the couplers between
    chains with intended couplings according to embedded_graph.

    Parameters
    ----------
    G : NetworkX graph
        The graph to be drawn

    layout : dict
        A dict of coordinates associated with each node in G.  Should
        be of the form {node: coordinate, ...}.  Coordinates will be
        treated as vectors, and should all have the same length.

    emb : dict
        A dict of chains associated with each node in G.  Should be
        of the form {node: chain, ...}.  Chains should be iterables
        of qubit labels (qubits are nodes in G).

    embedded_graph : NetworkX graph (optional, default None)
        A graph which contains all keys of emb as nodes.  If specified,
        edges of G will be considered interactions if and only if they
        exist between two chains of emb if their keys are connected by
        an edge in embedded_graph

    interaction_edges : list (optional, default None)
        A list of edges which will be used as interactions.

    show_labels: boolean (optional, default False)
        If show_labels is True, then each chain in emb is labelled with its key.

    chain_color : dict (optional, default None)
        A dict of colors associated with each key in emb.  Should be
        of the form {node: rgba_color, ...}.  Colors should be length-4
        tuples of floats between 0 and 1 inclusive. If chain_color is None,
        each chain will be assigned a different color.

    cmap : str or matplotlib colormap (optional, default None)
        A matplotlib colormap for coloring of chains.  Only used if chain_color
        is None.

    unused_color : tuple or color string (optional, default (0.9,0.9,0.9,1.0))
        The color to use for nodes and edges of G which are not involved
        in chains, and edges which are neither chain edges nor interactions.
        If unused_color is None, these nodes and edges will not be shown at all.

    overlapped_embedding: boolean (optional, default False)
        If overlapped_embedding is True, then chains in emb may overlap (contain
        the same vertices in G), and the drawing will display these overlaps as
        concentric circles.

    kwargs : optional keywords
       See networkx.draw_networkx() for a description of optional keywords,
       with the exception of the `pos` parameter which is not used by this
       function. If `linear_biases` or `quadratic_biases` are provided,
       any provided `node_color` or `edge_color` arguments are ignored.
    """
    try:
        import matplotlib.pyplot as plt
        import matplotlib as mpl
    except ImportError:
        raise ImportError("Matplotlib and numpy required for draw_chimera()")

    if nx.utils.is_string_like(unused_color):
        from matplotlib.colors import colorConverter
        alpha = kwargs.get('alpha', 1.0)
        unused_color = colorConverter.to_rgba(unused_color, alpha)

    if chain_color is None:
        import matplotlib.cm
        n = max(1., len(emb) - 1.)
        if cmap:
            color = matplotlib.cm.get_cmap(cmap)
        else:
            color = distinguishable_color_map(int(n + 1))
        var_i = {v: i for i, v in enumerate(emb)}
        chain_color = {v: color(i / n) for i, v in enumerate(emb)}

    if overlapped_embedding:
        bags = compute_bags(G, emb)
        base_node_size = kwargs.get('node_size', 100)
        node_size_dict = {v: base_node_size for v in G.nodes()}
        G, emb, interaction_edges = unoverlapped_embedding(
            G, emb, interaction_edges)
        for node, data in G.nodes(data=True):
            if 'dummy' in data:
                v, x = node
                layout[node] = layout[v]

        for v, bag in bags.items():
            for i, x in enumerate(bag):
                node_size_dict[(v, x)] = base_node_size * (len(bag) - i)**2

        kwargs['node_size'] = [node_size_dict[p] for p in G.nodes()]

    qlabel = {q: v for v, chain in emb.items() for q in chain}
    edgelist = []
    edge_color = []
    background_edgelist = []
    background_edge_color = []

    if interaction_edges is not None:
        interactions = nx.Graph()
        interactions.add_edges_from(interaction_edges)

        def show(p, q, u, v):
            return interactions.has_edge(p, q)
    elif embedded_graph is not None:

        def show(p, q, u, v):
            return embedded_graph.has_edge(u, v)
    else:

        def show(p, q, u, v):
            return True

    for (p, q) in G.edges():
        u = qlabel.get(p)
        v = qlabel.get(q)
        if u is None or v is None:
            ec = unused_color
        elif u == v:
            ec = chain_color.get(u)
        elif show(p, q, u, v):
            ec = (0, 0, 0, 1)
        else:
            ec = unused_color

        if ec == unused_color:
            background_edgelist.append((p, q))
            background_edge_color.append(ec)
        elif ec is not None:
            edgelist.append((p, q))
            edge_color.append(ec)

    nodelist = []
    node_color = []
    for p in G.nodes():
        u = qlabel.get(p)
        if u is None:
            pc = unused_color
        else:
            pc = chain_color.get(u)

        if pc is not None:
            nodelist.append(p)
            node_color.append(pc)

    labels = {}
    if show_labels:
        if overlapped_embedding:
            node_labels = {q: [] for q in bags.keys()}
            node_index = {p: i for i, p in enumerate(G.nodes())}
            for v in emb.keys():
                v_labelled = False
                chain = emb[v]
                for node in chain:
                    (q, _) = node
                    if len(bags[q]) == 1:
                        # if there's a node that only has this label, use that
                        labels[q] = str(v)
                        v_labelled = True
                        break
                if not v_labelled and chain:
                    # otherwise, pick a random node for this label
                    node = random.choice(list(chain))
                    (q, _) = node
                    node_labels[q].append(v)
            for q, label_vars in node_labels.items():
                x, y = layout[q]
                # TODO: find a better way of placing labels around the outside of nodes.
                # Currently, if the graph is resized, labels will appear at a strange distance from the vertices.
                # To fix this, the "scale" value below, rather than being a fixed constant, should be determined using
                # both the size of the nodes and the size of the coordinate space of the graph.
                scale = 0.1
                # spread the labels evenly around the node.
                for i, v in enumerate(label_vars):
                    theta = 2 * math.pi * i / len(label_vars)
                    new_x = x + scale * math.sin(theta)
                    new_y = y + scale * math.cos(theta)

                    plt.text(new_x,
                             new_y,
                             str(v),
                             color=node_color[node_index[(q, v)]],
                             horizontalalignment='center',
                             verticalalignment='center')
        else:
            for v in emb.keys():
                c = emb[v]
                labels[list(c)[0]] = str(v)

    # draw the background (unused) graph first
    if unused_color is not None:
        draw(G,
             layout,
             nodelist=nodelist,
             edgelist=background_edgelist,
             node_color=node_color,
             edge_color=background_edge_color,
             **kwargs)

    draw(G,
         layout,
         nodelist=nodelist,
         edgelist=edgelist,
         node_color=node_color,
         edge_color=edge_color,
         labels=labels,
         **kwargs)
コード例 #45
0
import scipy.cluster.hierarchy as sch
import cmap.io.gct as gct

from eVIP_predict import max_diff
from eVIP_compare import getSelfConnectivity, getConnectivity

#############
# CONSTANTS #
#############
DIFF_THRESH = 5
INFINITY = 10
DEF_PRED_COL = "prediction"

#RGB CODES
#GOF_COL = "#e31a1c"
GOF_COL = colorConverter.to_rgba("#ca0020", 1)
COF_PLUS_COL = colorConverter.to_rgba("#c2a5cf", 1)
COF_COL = colorConverter.to_rgba("#6a3d9a", 1)
COF_MINUS_COL = colorConverter.to_rgba("#c2a5cf", 1)
#LOF_COL = "#1f78b4"
LOF_COL = colorConverter.to_rgba("#0571b0", 1)
EQ_COL = colorConverter.to_rgba("#5aae61", 1)
INERT_COL = colorConverter.to_rgba("#000000", 1)
NI_COL = colorConverter.to_rgba("#ffffff", 1)

MAIN_MARKER = 'o'
NEG_MARKER = 'o'

XMIN = 0
XMAX = 4
YMIN = -3
コード例 #46
0
def draw_networkx_edges(G, pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=1.0,
                        arrowstyle='-|>',
                        arrowsize=10,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None,
                        ax=None,
                        arrows=True,
                        label=None,
                        node_size=300,
                        nodelist=None,
                        node_shape="o",
                        **kwds):
    """Draw the edges of the graph G.

    This draws only the edges of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    edgelist : collection of edge tuples
       Draw only specified edges(default=G.edges())

    width : float, or array of floats
       Line width of edges (default=1.0)

    edge_color : color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    style : string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)

    alpha : float
       The edge transparency (default=1.0)

    edge_ cmap : Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)

    edge_vmin,edge_vmax : floats
       Minimum and maximum for edge colormap scaling (default=None)

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.
       Note: Arrows will be the same color as edges.

    arrowstyle : str, optional (default='-|>')
       For directed graphs, choose the style of the arrow heads.
       See :py:class: `matplotlib.patches.ArrowStyle` for more
       options.

    arrowsize : int, optional (default=10)
       For directed graphs, choose the size of the arrow head head's length and
       width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute
       `mutation_scale` for more info.

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collection.LineCollection
        `LineCollection` of the edges

    list of matplotlib.patches.FancyArrowPatch
        `FancyArrowPatch` instances of the directed edges

    Depending whether the drawing includes arrows or not.

    Notes
    -----
    For directed graphs, arrows are drawn at the head end.  Arrows can be
    turned off with keyword arrows=False. Be sure to include `node_size` as a
    keyword argument; arrows are drawn considering the size of nodes.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))

    >>> G = nx.DiGraph()
    >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
    >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    >>> alphas = [0.3, 0.4, 0.5]
    >>> for i, arc in enumerate(arcs):  # change alpha values of arcs
    ...     arc.set_alpha(alphas[i])

    Also see the NetworkX drawing examples at
    https://networkx.github.io/documentation/latest/auto_examples/index.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib
        import matplotlib.pyplot as plt
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter, Colormap, Normalize
        from matplotlib.collections import LineCollection
        from matplotlib.patches import FancyArrowPatch
        import numpy as np
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if edgelist is None:
        edgelist = list(G.edges())

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    if nodelist is None:
        nodelist = list(G.nodes())

    # set edge positions
    edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width,)
    else:
        lw = width

    if not is_string_like(edge_color) \
            and cb.iterable(edge_color) \
            and len(edge_color) == len(edge_pos):
        if np.alltrue([is_string_like(c) for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple([colorConverter.to_rgba(c, alpha)
                                 for c in edge_color])
        elif np.alltrue([not is_string_like(c) for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if np.alltrue([cb.iterable(c) and len(c) in (3, 4)
                           for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError('edge_color must contain color names or numbers')
    else:
        if is_string_like(edge_color) or len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            msg = 'edge_color must be a color or list of one color per edge'
            raise ValueError(msg)

    if (not G.is_directed() or not arrows):
        edge_collection = LineCollection(edge_pos,
                                         colors=edge_colors,
                                         linewidths=lw,
                                         antialiaseds=(1,),
                                         linestyle=style,
                                         transOffset=ax.transData,
                                         )

        edge_collection.set_zorder(1)  # edges go behind nodes
        edge_collection.set_label(label)
        ax.add_collection(edge_collection)

        # Note: there was a bug in mpl regarding the handling of alpha values
        # for each line in a LineCollection. It was fixed in matplotlib by
        # r7184 and r7189 (June 6 2009). We should then not set the alpha
        # value globally, since the user can instead provide per-edge alphas
        # now.  Only set it globally if provided as a scalar.
        if isinstance(alpha, Number):
            edge_collection.set_alpha(alpha)

        if edge_colors is None:
            if edge_cmap is not None:
                assert(isinstance(edge_cmap, Colormap))
            edge_collection.set_array(np.asarray(edge_color))
            edge_collection.set_cmap(edge_cmap)
            if edge_vmin is not None or edge_vmax is not None:
                edge_collection.set_clim(edge_vmin, edge_vmax)
            else:
                edge_collection.autoscale()
        return edge_collection

    arrow_collection = None

    if G.is_directed() and arrows:
        # Note: Waiting for someone to implement arrow to intersection with
        # marker.  Meanwhile, this works well for polygons with more than 4
        # sides and circle.

        def to_marker_edge(marker_size, marker):
            if marker in "s^>v<d":  # `large` markers need extra space
                return np.sqrt(2 * marker_size) / 2
            else:
                return np.sqrt(marker_size) / 2

        # Draw arrows with `matplotlib.patches.FancyarrowPatch`
        arrow_collection = []
        mutation_scale = arrowsize  # scale factor of arrow head
        arrow_colors = edge_colors
        if arrow_colors is None:
            if edge_cmap is not None:
                assert(isinstance(edge_cmap, Colormap))
            else:
                edge_cmap = plt.get_cmap()  # default matplotlib colormap
            if edge_vmin is None:
                edge_vmin = min(edge_color)
            if edge_vmax is None:
                edge_vmax = max(edge_color)
            color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax)

        for i, (src, dst) in enumerate(edge_pos):
            x1, y1 = src
            x2, y2 = dst
            arrow_color = None
            line_width = None
            shrink_source = 0  # space from source to tail
            shrink_target = 0  # space from  head to target
            if cb.iterable(node_size):  # many node sizes
                src_node, dst_node = edgelist[i]
                index_node = nodelist.index(dst_node)
                marker_size = node_size[index_node]
                shrink_target = to_marker_edge(marker_size, node_shape)
            else:
                shrink_target = to_marker_edge(node_size, node_shape)
            if arrow_colors is None:
                arrow_color = edge_cmap(color_normal(edge_color[i]))
            elif len(arrow_colors) > 1:
                arrow_color = arrow_colors[i]
            else:
                arrow_color = arrow_colors[0]
            if len(lw) > 1:
                line_width = lw[i]
            else:
                line_width = lw[0]
            arrow = FancyArrowPatch((x1, y1), (x2, y2),
                                    arrowstyle=arrowstyle,
                                    shrinkA=shrink_source,
                                    shrinkB=shrink_target,
                                    mutation_scale=mutation_scale,
                                    color=arrow_color,
                                    linewidth=line_width,
                                    zorder=1)  # arrows go behind nodes

            # There seems to be a bug in matplotlib to make collections of
            # FancyArrowPatch instances. Until fixed, the patches are added
            # individually to the axes instance.
            arrow_collection.append(arrow)
            ax.add_patch(arrow)

    # update view
    minx = np.amin(np.ravel(edge_pos[:, :, 0]))
    maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
    miny = np.amin(np.ravel(edge_pos[:, :, 1]))
    maxy = np.amax(np.ravel(edge_pos[:, :, 1]))

    w = maxx - minx
    h = maxy - miny
    padx,  pady = 0.05 * w, 0.05 * h
    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    return arrow_collection
コード例 #47
0
def eVIP_run_main(pred_file=None,
                  ref_allele_mode=None,
                  y_thresh=None,
                  x_thresh=None,
                  use_c_pval=None,
                  annotate=None,
                  by_gene_color=None,
                  pdf=None,
                  xmin=None,
                  xmax=None,
                  ymin=None,
                  ymax=None,
                  out_dir=None):
    x_thresh = float(x_thresh)
    y_thresh = float(y_thresh)

    # setting default values
    xmin = float(xmin) if xmin != None else float(0.0)
    xmax = float(xmax) if xmax != None else float(4.0)
    ymin = float(ymin) if ymin != None else float(-3.0)
    ymax = float(ymax) if ymax != None else float(3.0)

    pred_file = open(pred_file)
    if pdf:
        format = "pdf"
    else:
        format = "png"

    if os.path.exists(out_dir):
        out_dir = os.path.abspath(out_dir)
    else:
        os.mkdir(out_dir)
        out_dir = os.path.abspath(out_dir)
        print "Creating output directory: %s" % out_dir

    x_thresh = getNegLog10(x_thresh, xmax)
    y_thresh = getNegLog10(y_thresh, ymax)
    annotate = annotate
    pred_col = DEF_PRED_COL
    ref_allele_mode = ref_allele_mode

    gene2type = None
    if by_gene_color:
        gene2type = parseGeneColor(by_gene_color)

    (gene2mut_wt, gene2mut_wt_rep_p, gene2neg_log_p, gene2diff_score,
     gene2allele, gene2col, gene_type2pred2count,
     gene2markerstyle) = parse_pred_file(pred_file, x_thresh, y_thresh,
                                         pred_col, use_c_pval, gene2type,
                                         ref_allele_mode, xmax, ymax)

    if gene2type:
        # Print out gene type and prediction counts
        # for gene_type in gene_type2pred2count:
        #     print "###%s###" % gene_type
        #     for pred in gene_type2pred2count[gene_type]:
        #         print "%s\t%s" % (pred, gene_type2pred2count[gene_type][pred])

        gene_type2data = {
            "ONC": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            },
            "TSG": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            },
            "TSG_noTP53": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            },
            "ONC-NEG": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            }
        }
    all_mut_wt = []
    all_mut_wt_rep_p = []
    all_neg_log_p = []
    all_col = []
    all_diff_score = []
    all_markerstyle = []
    recs = []
    predictions = ["GOF", "LOF", "COF", "Neutral"]

    for gene in gene2allele:

        this_fig = plt.figure()
        ax = this_fig.add_subplot(111)

        #        plt.axhline(y=0, color="grey")

        all_mut_wt.extend(gene2mut_wt[gene])
        all_mut_wt_rep_p.extend(gene2mut_wt_rep_p[gene])
        all_neg_log_p.extend(gene2neg_log_p[gene])
        all_col.extend(gene2col[gene])
        all_diff_score.extend(gene2diff_score[gene])
        all_markerstyle.extend(gene2markerstyle[gene])

        if gene not in gene2type:
            gene2type[gene] = "UNKN"

        # Add to gene-type specific plot data
        for gene_type in gene_type2data:
            gene_type2data[gene_type]["mut_wt"].extend(gene2mut_wt[gene])
            gene_type2data[gene_type]["mut_wt_rep_p"].extend(
                gene2mut_wt_rep_p[gene])
            gene_type2data[gene_type]["neg_log_p"].extend(gene2neg_log_p[gene])
            gene_type2data[gene_type]["markerstyle"].extend(
                gene2markerstyle[gene])

            gene_root = gene.split("_")[0]
            if gene_type == "TSG_noTP53":
                if gene2type[gene_root] == "TSG" and gene != "TP53":
                    gene_type2data[gene_type]["col"].extend(gene2col[gene])
                else:
                    gene_type2data[gene_type]["col"].extend(
                        makeGrey(gene2col[gene]))
            else:
                if gene2type[gene_root] == gene_type:
                    gene_type2data[gene_type]["col"].extend(gene2col[gene])
                else:
                    gene_type2data[gene_type]["col"].extend(
                        makeGrey(gene2col[gene]))

        (main_markers, neg_markers) = split_data(gene2markerstyle[gene],
                                                 gene2neg_log_p[gene],
                                                 gene2mut_wt_rep_p[gene],
                                                 gene2col[gene])

        try:
            plt.scatter(main_markers["x"],
                        main_markers["y"],
                        s=MARKER_SIZE,
                        c=main_markers["col"],
                        marker=MAIN_MARKER,
                        edgecolors="none",
                        linewidth=0)
        except:
            pdb.set_trace()

        plt.scatter(neg_markers["x"],
                    neg_markers["y"],
                    s=MARKER_SIZE,
                    c=neg_markers["col"],
                    marker=NEG_MARKER,
                    linewidth=4)

        for i in range(len(gene2neg_log_p[gene])):
            this_col = gene2col[gene][i]
            if this_col == colorConverter.to_rgba("#ffffff", 1):  # white
                this_col = "black"
            plt.plot([0, gene2neg_log_p[gene][i]],
                     [0, gene2mut_wt_rep_p[gene][i]],
                     color=this_col,
                     linewidth=SPARKLER_LINEWIDTH)

        if annotate:
            for i in range(len(gene2allele[gene])):
                ax.annotate(
                    gene2allele[gene][i],
                    (gene2neg_log_p[gene][i], gene2mut_wt_rep_p[gene][i]),
                    textcoords='data')

        plt.axvline(x=x_thresh, color="grey", ls=THRESH_LS)

        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)

        if use_c_pval:
            ax.set_xlabel("-log10(corrected p-val)")
        else:
            ax.set_xlabel("-log10(p-val)")
        ax.set_ylabel("impact direction score")

        ax.text(100,
                -7,
                "MUT robustness < WT robustness",
                fontsize="small",
                ha="center")
        ax.text(100,
                7,
                "MUT robustness > WT robustness",
                fontsize="small",
                ha="center")

        predictions = ["GOF", "LOF", "COF", "Neutral"]
        colors = [GOF_COL, LOF_COL, COF_COL, "black"]

        for i in range(len(colors)):
            recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i]))

        this_fig.savefig("%s/%s_spark_plots.%s" % (out_dir, gene, format),
                         format=format)

        plt.close(this_fig)

    # GENE-TYPE plots
    for legend_flag in ["legend_on", "legend_off"]:
        for gene_type in gene_type2data:
            this_fig = plt.figure()
            ax = this_fig.add_subplot(111)

            #            plt.axhline(y=0, color="grey")

            # Add lines
            for i in range(len(gene_type2data[gene_type]["mut_wt"])):
                this_col = gene_type2data[gene_type]["col"][i]
                if this_col == colorConverter.to_rgba("#ffffff", 1):  # white
                    this_col = INERT_COL
                plt.plot(
                    [0, gene_type2data[gene_type]["neg_log_p"][i]],
                    [0, gene_type2data[gene_type]["mut_wt_rep_p"][i]],
                    #                         [0, gene_type2data[gene_type]["mut_wt"][i]],
                    color=this_col,
                    #                         alpha=0.5,
                    linewidth=SPARKLER_LINEWIDTH)

            (main_markers, neg_markers) = split_data(
                gene_type2data[gene_type]["markerstyle"],
                gene_type2data[gene_type]["neg_log_p"],
                gene_type2data[gene_type]["mut_wt_rep_p"],
                gene_type2data[gene_type]["col"])

            plt.scatter(main_markers["x"],
                        main_markers["y"],
                        s=MARKER_SIZE,
                        c=main_markers["col"],
                        marker=MAIN_MARKER,
                        edgecolors="none",
                        linewidth=0)

            plt.scatter(neg_markers["x"],
                        neg_markers["y"],
                        s=MARKER_SIZE,
                        c=neg_markers["col"],
                        marker=NEG_MARKER,
                        linewidth=4)

            plt.axvline(x=x_thresh, color="grey", ls=THRESH_LS)

            plt.xlim(xmin, xmax)
            plt.ylim(ymin, ymax)

            if use_c_pval:
                ax.set_xlabel("-log10(corrected p-val)")
            else:
                ax.set_xlabel("-log10(p-val)")
            ax.set_ylabel("impact direction score")

            ax.text(100,
                    -7,
                    "MUT robustness < WT robustness",
                    fontsize="small",
                    ha="center")
            ax.text(100,
                    7,
                    "MUT robustness > WT robustness",
                    fontsize="small",
                    ha="center")

            if legend_flag == "legend_on":
                plt.legend(recs,
                           predictions,
                           loc="lower right",
                           fontsize='xx-small',
                           title="prediction")

            this_fig.savefig("%s/%s_spark_plots_%s.%s" %
                             (out_dir, gene_type, legend_flag, format),
                             format=format)

            plt.close(this_fig)

    # final plot
    this_fig = plt.figure()
    ax = this_fig.add_subplot(111)

    # Add lines
    for i in range(len(all_diff_score)):
        this_col = all_col[i]
        if this_col == "white":
            this_col = "black"
        plt.plot([0, all_neg_log_p[i]], [0, all_mut_wt_rep_p[i]],
                 color=this_col,
                 alpha=0.25,
                 linewidth=ALL_SPARKLER_LINEWIDTH)

    (main_markers, neg_markers) = split_data(all_markerstyle, all_neg_log_p,
                                             all_mut_wt_rep_p, all_col)

    plt.scatter(main_markers["x"],
                main_markers["y"],
                s=MARKER_SIZE,
                c=main_markers["col"],
                marker=MAIN_MARKER,
                edgecolors="none",
                linewidth=0)

    plt.scatter(neg_markers["x"],
                neg_markers["y"],
                s=MARKER_SIZE,
                c=neg_markers["col"],
                marker=NEG_MARKER,
                linewidth=4)

    plt.axvline(x=x_thresh, color="grey", ls=THRESH_LS)

    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)

    if use_c_pval:
        ax.set_xlabel("-log10(corrected p-val)")
    else:
        ax.set_xlabel("-log10(p-val)")
    ax.set_ylabel("impact direction score")

    this_fig.savefig("%s/all_spark_plots.%s" % (out_dir, format),
                     format=format)

    plt.close(this_fig)
コード例 #48
0
ファイル: DrawNetwork.py プロジェクト: 1kastner/Tag2Network
def draw_nx_tapered_edges(G,
                          pos,
                          edgelist=None,
                          width=0.5,
                          edge_color='k',
                          style='solid',
                          alpha=1.0,
                          edge_cmap=None,
                          edge_vmin=None,
                          edge_vmax=None,
                          ax=None,
                          label=None,
                          highlight=None,
                          tapered=False,
                          **kwds):
    """Draw the edges of the graph G.
    This draws only the edges of the graph G.
    Parameters
    ----------
    G : graph
       A networkx graph
    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.
    edgelist : collection of edge tuples
       Draw only specified edges(default=G.edges())
    width : float, or array of floats
       Line width of edges (default=1.0)
    edge_color : color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.
    style : string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)
    alpha : float
       The edge transparency (default=1.0)
    edge_ cmap : Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)
    edge_vmin,edge_vmax : floats
       Minimum and maximum for edge colormap scaling (default=None)
    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.
    label : [None| string]
       Label for legend
    Returns
    -------
    matplotlib.collection.LineCollection
        `LineCollection` of the edges
    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G))
    Also see the NetworkX drawing examples at
    http://networkx.github.io/documentation/latest/gallery.html
    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    if ax is None:
        ax = plt.gca()

    if edgelist is None:
        edgelist = list(G.edges())

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    if highlight is not None and (isinstance(edge_color, basestring)
                                  or not cb.iterable(edge_color)):
        idMap = {}
        nodes = G.nodes()
        for i in range(len(nodes)):
            idMap[nodes[i]] = i
        ecol = [edge_color] * len(edgelist)
        eHighlight = [
            highlight[idMap[edge[0]]] or highlight[idMap[edge[1]]]
            for edge in edgelist
        ]
        for i in range(len(eHighlight)):
            if eHighlight[i]:
                ecol[i] = '0.0'
        edge_color = ecol

    # set edge positions
    if not cb.iterable(width):
        lw = np.full(len(edgelist), width)
    else:
        lw = width

    edge_pos = []
    wdScale = 0.01
    for i in range(len(edgelist)):
        e = edgelist[i]
        w = wdScale * lw[i] / 2
        p0 = pos[e[0]]
        p1 = pos[e[1]]
        dx = p1[0] - p0[0]
        dy = p1[1] - p0[1]
        l = math.sqrt(dx * dx + dy * dy)
        edge_pos.append(
            ((p0[0] + w * dy / l, p0[1] - w * dx / l),
             (p0[0] - w * dy / l, p0[1] + w * dx / l), (p1[0], p1[1])))

    edge_vertices = np.asarray(edge_pos)

    if not isinstance(edge_color, basestring) \
           and cb.iterable(edge_color) \
           and len(edge_color) == len(edge_vertices):
        if np.alltrue([isinstance(c, basestring) for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple(
                [colorConverter.to_rgba(c, alpha) for c in edge_color])
        elif np.alltrue([not isinstance(c, basestring) for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if np.alltrue(
                [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError(
                'edge_color must consist of either color names or numbers')
    else:
        if isinstance(edge_color, basestring) or len(edge_color) == 1:
            edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError(
                'edge_color must be a single color or list of exactly m colors where m is the number or edges'
            )

    if tapered:
        edge_collection = PolyCollection(
            edge_vertices,
            facecolors=edge_colors,
            linewidths=0,
            antialiaseds=(1, ),
            transOffset=ax.transData,
        )
    else:
        edge_collection = LineCollection(
            edge_pos,
            colors=edge_colors,
            linewidths=lw,
            antialiaseds=(1, ),
            linestyle=style,
            transOffset=ax.transData,
        )

    edge_collection.set_zorder(1)  # edges go behind nodes
    edge_collection.set_label(label)
    ax.add_collection(edge_collection)

    # Note: there was a bug in mpl regarding the handling of alpha values for
    # each line in a LineCollection.  It was fixed in matplotlib in r7184 and
    # r7189 (June 6 2009).  We should then not set the alpha value globally,
    # since the user can instead provide per-edge alphas now.  Only set it
    # globally if provided as a scalar.
    if cb.is_numlike(alpha):
        edge_collection.set_alpha(alpha)

    if edge_colors is None:
        if edge_cmap is not None:
            assert (isinstance(edge_cmap, Colormap))
        edge_collection.set_array(np.asarray(edge_color))
        edge_collection.set_cmap(edge_cmap)
        if edge_vmin is not None or edge_vmax is not None:
            edge_collection.set_clim(edge_vmin, edge_vmax)
        else:
            edge_collection.autoscale()

    # update view
    minx = np.amin(np.ravel(edge_vertices[:, :, 0]))
    maxx = np.amax(np.ravel(edge_vertices[:, :, 0]))
    miny = np.amin(np.ravel(edge_vertices[:, :, 1]))
    maxy = np.amax(np.ravel(edge_vertices[:, :, 1]))

    w = maxx - minx
    h = maxy - miny
    padx, pady = 0.05 * w, 0.05 * h
    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    return edge_collection
コード例 #49
0
def main():

    opt_parser = OptionParser()

    # Add Options. Required options should have default=None
    opt_parser.add_option("--pred_file",
                          dest="pred_file",
                          type="string",
                          help="""File containing the mutation impact
                                  predictions""",
                          default=None)
    opt_parser.add_option("--ref_allele_mode",
                          dest="ref_allele_mode",
                          action="store_true",
                          help="""Instead of organizing plots by gene, will use
                                  the wt column to determine what are the
                                  reference alleles.""",
                          default=False)
    opt_parser.add_option("--x_thresh",
                          dest="x_thresh",
                          type="float",
                          help="Threshold of significance",
                          default=None)
    opt_parser.add_option("--y_thresh",
                          dest="y_thresh",
                          type="float",
                          help="Threshold of impact direction",
                          default=None)
    opt_parser.add_option("--use_c_pval",
                          dest="use_c_pval",
                          action="store_true",
                          help="Use corrected p-val instead of raw p-val",
                          default=False)
    opt_parser.add_option("--annotate",
                          dest="annotate",
                          action="store_true",
                          help="Will add allele labels to points.",
                          default=False)
    opt_parser.add_option("--by_gene_color",
                          dest="by_gene_color",
                          type="string",
                          help="""File containing labels and colors for
                                  gene-cenric plot""",
                          default=None)
    opt_parser.add_option("--out_dir",
                          dest="out_dir",
                          type="string",
                          help="Output directory to put figures",
                          default=None)
    opt_parser.add_option("--pdf",
                          dest="pdf",
                          action="store_true",
                          help="Will print plots in pdf format instead of png",
                          default=False)
    opt_parser.add_option("--xmin",
                          dest="xmin",
                          type="float",
                          help="Min value of x-axis. DEF=%d" % XMIN,
                          default=XMIN)
    opt_parser.add_option("--xmax",
                          dest="xmax",
                          type="float",
                          help="Max value of x-axis. DEF=%d" % XMAX,
                          default=XMAX)
    opt_parser.add_option("--ymin",
                          dest="ymin",
                          type="float",
                          help="Min value of y-axis. DEF=%d" % YMIN,
                          default=YMIN)
    opt_parser.add_option("--ymax",
                          dest="ymax",
                          type="float",
                          help="Max value of y-axis. DEF=%d" % YMAX,
                          default=YMAX)

    (options, args) = opt_parser.parse_args()

    # validate the command line arguments
    opt_parser.check_required("--pred_file")
    opt_parser.check_required("--x_thresh")
    opt_parser.check_required("--y_thresh")
    opt_parser.check_required("--by_gene_color")

    opt_parser.check_required("--out_dir")

    pred_file = open(options.pred_file)
    if options.pdf:
        format = "pdf"
    else:
        format = "png"

    if os.path.exists(options.out_dir):
        out_dir = os.path.abspath(options.out_dir)
    else:
        os.mkdir(options.out_dir)
        out_dir = os.path.abspath(options.out_dir)
        print "Creating output directory: %s" % out_dir

    x_thresh = getNegLog10(options.x_thresh, options.xmax)
    y_thresh = getNegLog10(options.y_thresh, options.ymax)
    annotate = options.annotate
    pred_col = DEF_PRED_COL
    ref_allele_mode = options.ref_allele_mode

    use_c_pval = options.use_c_pval

    xmin = options.xmin
    xmax = options.xmax
    ymin = options.ymin
    ymax = options.ymax

    gene2type = None
    if options.by_gene_color:
        gene2type = parseGeneColor(options.by_gene_color)

    (gene2mut_wt, gene2mut_wt_rep_p, gene2neg_log_p, gene2diff_score,
     gene2allele, gene2col, gene_type2pred2count,
     gene2markerstyle) = parse_pred_file(pred_file, x_thresh, y_thresh,
                                         pred_col, use_c_pval, gene2type,
                                         ref_allele_mode, xmax, ymax)

    if gene2type:
        # Print out gene type and prediction counts
        # for gene_type in gene_type2pred2count:
        #     print "###%s###" % gene_type
        #     for pred in gene_type2pred2count[gene_type]:
        #         print "%s\t%s" % (pred, gene_type2pred2count[gene_type][pred])

        gene_type2data = {
            "ONC": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            },
            "TSG": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            },
            "TSG_noTP53": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            },
            "ONC-NEG": {
                "mut_wt": [],
                "mut_wt_rep_p": [],
                "neg_log_p": [],
                "markerstyle": [],
                "col": []
            }
        }
    all_mut_wt = []
    all_mut_wt_rep_p = []
    all_neg_log_p = []
    all_col = []
    all_diff_score = []
    all_markerstyle = []
    predictions = ["GOF", "LOF", "COF", "Neutral"]

    for gene in gene2allele:

        this_fig = plt.figure()
        ax = this_fig.add_subplot(111)

        #        plt.axhline(y=0, color="grey")

        all_mut_wt.extend(gene2mut_wt[gene])
        all_mut_wt_rep_p.extend(gene2mut_wt_rep_p[gene])
        all_neg_log_p.extend(gene2neg_log_p[gene])
        all_col.extend(gene2col[gene])
        all_diff_score.extend(gene2diff_score[gene])
        all_markerstyle.extend(gene2markerstyle[gene])

        if gene not in gene2type:
            gene2type[gene] = "UNKN"

        # Add to gene-type specific plot data
        for gene_type in gene_type2data:
            gene_type2data[gene_type]["mut_wt"].extend(gene2mut_wt[gene])
            gene_type2data[gene_type]["mut_wt_rep_p"].extend(
                gene2mut_wt_rep_p[gene])
            gene_type2data[gene_type]["neg_log_p"].extend(gene2neg_log_p[gene])
            gene_type2data[gene_type]["markerstyle"].extend(
                gene2markerstyle[gene])

            gene_root = gene.split("_")[0]
            if gene_type == "TSG_noTP53":
                if gene2type[gene_root] == "TSG" and gene != "TP53":
                    gene_type2data[gene_type]["col"].extend(gene2col[gene])
                else:
                    gene_type2data[gene_type]["col"].extend(
                        makeGrey(gene2col[gene]))
            else:
                if gene2type[gene_root] == gene_type:
                    gene_type2data[gene_type]["col"].extend(gene2col[gene])
                else:
                    gene_type2data[gene_type]["col"].extend(
                        makeGrey(gene2col[gene]))

        (main_markers, neg_markers) = split_data(gene2markerstyle[gene],
                                                 gene2neg_log_p[gene],
                                                 gene2mut_wt_rep_p[gene],
                                                 gene2col[gene])

        try:
            plt.scatter(main_markers["x"],
                        main_markers["y"],
                        s=MARKER_SIZE,
                        c=main_markers["col"],
                        marker=MAIN_MARKER,
                        edgecolors="none",
                        linewidth=0)
        except:
            pdb.set_trace()

        plt.scatter(neg_markers["x"],
                    neg_markers["y"],
                    s=MARKER_SIZE,
                    c=neg_markers["col"],
                    marker=NEG_MARKER,
                    linewidth=4)

        for i in range(len(gene2neg_log_p[gene])):
            this_col = gene2col[gene][i]
            if this_col == colorConverter.to_rgba("#ffffff", 1):  # white
                this_col = "black"
            plt.plot([0, gene2neg_log_p[gene][i]],
                     [0, gene2mut_wt_rep_p[gene][i]],
                     color=this_col,
                     linewidth=SPARKLER_LINEWIDTH)

        if annotate:
            for i in range(len(gene2allele[gene])):
                ax.annotate(
                    gene2allele[gene][i],
                    (gene2neg_log_p[gene][i], gene2mut_wt_rep_p[gene][i]),
                    textcoords='data')

        plt.axvline(x=x_thresh, color="grey", ls=THRESH_LS)

        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)

        if use_c_pval:
            ax.set_xlabel("-log10(corrected p-val)")
        else:
            ax.set_xlabel("-log10(p-val)")
        ax.set_ylabel("impact direction score")

        ax.text(100,
                -7,
                "MUT robustness < WT robustness",
                fontsize="small",
                ha="center")
        ax.text(100,
                7,
                "MUT robustness > WT robustness",
                fontsize="small",
                ha="center")

        # predictions = ["GOF", "LOF", "COF", "Neutral"]
        colors = [GOF_COL, LOF_COL, COF_COL, "black"]

        recs = []
        for i in range(len(colors)):
            recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i]))

        this_fig.savefig("%s/%s_spark_plots.%s" % (out_dir, gene, format),
                         format=format)

        plt.close(this_fig)

    # GENE-TYPE plots
    for legend_flag in ["legend_on", "legend_off"]:
        for gene_type in gene_type2data:
            this_fig = plt.figure()
            ax = this_fig.add_subplot(111)

            #            plt.axhline(y=0, color="grey")

            # Add lines
            for i in range(len(gene_type2data[gene_type]["mut_wt"])):
                this_col = gene_type2data[gene_type]["col"][i]
                if this_col == colorConverter.to_rgba("#ffffff", 1):  # white
                    this_col = INERT_COL
                plt.plot(
                    [0, gene_type2data[gene_type]["neg_log_p"][i]],
                    [0, gene_type2data[gene_type]["mut_wt_rep_p"][i]],
                    #                         [0, gene_type2data[gene_type]["mut_wt"][i]],
                    color=this_col,
                    #                         alpha=0.5,
                    linewidth=SPARKLER_LINEWIDTH)

            (main_markers, neg_markers) = split_data(
                gene_type2data[gene_type]["markerstyle"],
                gene_type2data[gene_type]["neg_log_p"],
                gene_type2data[gene_type]["mut_wt_rep_p"],
                gene_type2data[gene_type]["col"])

            plt.scatter(main_markers["x"],
                        main_markers["y"],
                        s=MARKER_SIZE,
                        c=main_markers["col"],
                        marker=MAIN_MARKER,
                        edgecolors="none",
                        linewidth=0)

            plt.scatter(neg_markers["x"],
                        neg_markers["y"],
                        s=MARKER_SIZE,
                        c=neg_markers["col"],
                        marker=NEG_MARKER,
                        linewidth=4)

            plt.axvline(x=x_thresh, color="grey", ls=THRESH_LS)

            plt.xlim(xmin, xmax)
            plt.ylim(ymin, ymax)

            if use_c_pval:
                ax.set_xlabel("-log10(corrected p-val)")
            else:
                ax.set_xlabel("-log10(p-val)")
            ax.set_ylabel("impact direction score")

            ax.text(100,
                    -7,
                    "MUT robustness < WT robustness",
                    fontsize="small",
                    ha="center")
            ax.text(100,
                    7,
                    "MUT robustness > WT robustness",
                    fontsize="small",
                    ha="center")

            if legend_flag == "legend_on":
                plt.legend(recs,
                           predictions,
                           loc="lower right",
                           fontsize='xx-small',
                           title="prediction")

            this_fig.savefig("%s/%s_spark_plots_%s.%s" %
                             (out_dir, gene_type, legend_flag, format),
                             format=format)

            plt.close(this_fig)

    # final plot
    this_fig = plt.figure()
    ax = this_fig.add_subplot(111)

    # Add lines
    for i in range(len(all_diff_score)):
        this_col = all_col[i]
        if this_col == "white":
            this_col = "black"
        plt.plot([0, all_neg_log_p[i]], [0, all_mut_wt_rep_p[i]],
                 color=this_col,
                 alpha=0.25,
                 linewidth=ALL_SPARKLER_LINEWIDTH)

    (main_markers, neg_markers) = split_data(all_markerstyle, all_neg_log_p,
                                             all_mut_wt_rep_p, all_col)

    plt.scatter(main_markers["x"],
                main_markers["y"],
                s=MARKER_SIZE,
                c=main_markers["col"],
                marker=MAIN_MARKER,
                edgecolors="none",
                linewidth=0)

    plt.scatter(neg_markers["x"],
                neg_markers["y"],
                s=MARKER_SIZE,
                c=neg_markers["col"],
                marker=NEG_MARKER,
                linewidth=4)

    plt.axvline(x=x_thresh, color="grey", ls=THRESH_LS)

    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)

    if use_c_pval:
        ax.set_xlabel("-log10(corrected p-val)")
    else:
        ax.set_xlabel("-log10(p-val)")
    ax.set_ylabel("impact direction score")

    this_fig.savefig("%s/all_spark_plots.%s" % (out_dir, format),
                     format=format)

    plt.close(this_fig)

    sys.exit(0)
コード例 #50
0
test_set = Ising(DATA_PATH, train=False)

test_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=True)

net = Network()
net.load_state_dict(torch.load(MODEL_PATH))

if CUDA:
    net.to(torch.device('cuda'))
net.eval()

losses, targets, predictions = evaluate(net, test_loader, CUDA=CUDA)

r = spearmanr(targets, predictions).correlation

loss_color = colorConverter.to_rgba('mediumseagreen', alpha=.5)

markerOptions = dict(markerfacecolor='none', markeredgewidth=1.5)

fig, ax = plt.subplots(figsize=(10, 6))

ax.title.set_text(f"Spearman Correlation Coefficient r={r:.4f}")

ax.plot(targets,
        predictions,
        linestyle='None',
        marker='s',
        color='blue',
        **markerOptions)
ax.set_ylabel('Predicted Temperature T/T$_C$')
ax.set_xlabel("Ground truth T/T$_C$")
コード例 #51
0
def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
    """Apply an alpha (or list of alphas) to the colors provided.

    Parameters
    ----------

    colors : color string, or array of floats
       Color of element. Can be a single color format string (default='r'),
       or a  sequence of colors with the same length as nodelist.
       If numeric values are specified they will be mapped to
       colors using the cmap and vmin,vmax parameters.  See
       matplotlib.scatter for more details.

    alpha : float or array of floats
       Alpha values for elements. This can be a single alpha value, in
       which case it will be applied to all the elements of color. Otherwise,
       if it is an array, the elements of alpha will be applied to the colors
       in order (cycling through alpha multiple times if necessary).

    elem_list : array of networkx objects
       The list of elements which are being colored. These could be nodes,
       edges or labels.

    cmap : matplotlib colormap
       Color map for use if colors is a list of floats corresponding to points
       on a color mapping.

    vmin, vmax : float
       Minimum and maximum values for normalizing colors if a color mapping is
       used.

    Returns
    -------

    rgba_colors : numpy ndarray
        Array containing RGBA format values for each of the node colours.

    """
    from itertools import islice, cycle

    try:
        import numpy as np
        from matplotlib.colors import colorConverter
        import matplotlib.cm as cm
    except ImportError:
        raise ImportError("Matplotlib required for draw()")

    # If we have been provided with a list of numbers as long as elem_list,
    # apply the color mapping.
    if len(colors) == len(elem_list) and isinstance(colors[0], Number):
        mapper = cm.ScalarMappable(cmap=cmap)
        mapper.set_clim(vmin, vmax)
        rgba_colors = mapper.to_rgba(colors)
    # Otherwise, convert colors to matplotlib's RGB using the colorConverter
    # object.  These are converted to numpy ndarrays to be consistent with the
    # to_rgba method of ScalarMappable.
    else:
        try:
            rgba_colors = np.array([colorConverter.to_rgba(colors)])
        except ValueError:
            rgba_colors = np.array([colorConverter.to_rgba(color)
                                    for color in colors])
    # Set the final column of the rgba_colors to have the relevant alpha values
    try:
        # If alpha is longer than the number of colors, resize to the number of
        # elements.  Also, if rgba_colors.size (the number of elements of
        # rgba_colors) is the same as the number of elements, resize the array,
        # to avoid it being interpreted as a colormap by scatter()
        if len(alpha) > len(rgba_colors) or rgba_colors.size == len(elem_list):
            rgba_colors = np.resize(rgba_colors, (len(elem_list), 4))
            rgba_colors[1:, 0] = rgba_colors[0, 0]
            rgba_colors[1:, 1] = rgba_colors[0, 1]
            rgba_colors[1:, 2] = rgba_colors[0, 2]
        rgba_colors[:,  3] = list(islice(cycle(alpha), len(rgba_colors)))
    except TypeError:
        rgba_colors[:, -1] = alpha
    return rgba_colors
コード例 #52
0
ファイル: report_estimation.py プロジェクト: jvail/vmango
 def cc(arg): return colorConverter.to_rgba(arg, alpha=0.6)
 colors = [cc('r'), cc('g'), cc('b'), cc('y')]
コード例 #53
0
#

fig = plt.figure(1)

plt.plot(aa, bb, linewidth=1.0, color='b')
plt.grid(True)
plt.xlabel('Time (sec)')
plt.title('Input Time History')

from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from matplotlib.colors import colorConverter

fig = plt.figure(2)
ax = fig.gca(projection='3d')

cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6)

verts = []

ys = zeros(mk, 'f')

zs = zeros(mk, 'f')

maxz = 0

for i in range(0, NW):
    for j in range(0, mk):
        zs[j] = store_p[i][j]

        if zs[j] > maxz:
            maxz = zs[j]
コード例 #54
0
    def plot_surface(self, X, Y, Z, *args, **kwargs):
        '''
        Create a surface plot.

        By default it will be colored in shades of a solid color,
        but it also supports color mapping by supplying the *cmap*
        argument.

        ============= ================================================
        Argument      Description
        ============= ================================================
        *X*, *Y*, *Z* Data values as numpy.arrays
        *rstride*     Array row stride (step size)
        *cstride*     Array column stride (step size)
        *color*       Color of the surface patches
        *cmap*        A colormap for the surface patches.
        *facecolors*  Face colors for the individual patches
        *norm*        An instance of Normalize to map values to colors
        *vmin*        Minimum value to map
        *vmax*        Maximum value to map
        *shade*       Whether to shade the facecolors
        ============= ================================================

        Other arguments are passed on to
        :func:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection.__init__`
        '''

        had_data = self.has_data()

        rows, cols = Z.shape
        rstride = kwargs.pop('rstride', 10)
        cstride = kwargs.pop('cstride', 10)

        if 'facecolors' in kwargs:
            fcolors = kwargs.pop('facecolors')
        else:
            color = np.array(colorConverter.to_rgba(kwargs.pop('color', 'b')))
            fcolors = None

        cmap = kwargs.get('cmap', None)
        norm = kwargs.pop('norm', None)
        vmin = kwargs.pop('vmin', None)
        vmax = kwargs.pop('vmax', None)
        linewidth = kwargs.get('linewidth', None)
        shade = kwargs.pop('shade', cmap is None)
        lightsource = kwargs.pop('lightsource', None)

        # Shade the data
        if shade and cmap is not None and fcolors is not None:
            fcolors = self._shade_colors_lightsource(Z, cmap, lightsource)

        polys = []
        # Only need these vectors to shade if there is no cmap
        if cmap is None and shade :
            totpts = int(np.ceil(float(rows - 1) / rstride) *
                         np.ceil(float(cols - 1) / cstride))
            v1 = np.empty((totpts, 3))
            v2 = np.empty((totpts, 3))
            # This indexes the vertex points
            which_pt = 0


        #colset contains the data for coloring: either average z or the facecolor
        colset = []
        for rs in xrange(0, rows-1, rstride):
            for cs in xrange(0, cols-1, cstride):  
                ps = []
                for a in (X, Y, Z) :
                    ztop = a[rs,cs:min(cols, cs+cstride+1)]
                    zleft = a[rs+1:min(rows, rs+rstride+1),
                              min(cols-1, cs+cstride)]
                    zbase = a[min(rows-1, rs+rstride), cs:min(cols, cs+cstride+1):][::-1]
                    zright = a[rs:min(rows-1, rs+rstride):, cs][::-1]
                    z = np.concatenate((ztop, zleft, zbase, zright))
                    ps.append(z)

                # The construction leaves the array with duplicate points, which
                # are removed here.
                ps = zip(*ps)
                lastp = np.array([])
                ps2 = [ps[0]] + [ps[i] for i in xrange(1, len(ps)) if ps[i] != ps[i-1]]
                avgzsum = sum(p[2] for p in ps2)
                polys.append(ps2)

                if fcolors is not None:
                    colset.append(fcolors[rs][cs])
                else:
                    colset.append(avgzsum / len(ps2))

                # Only need vectors to shade if no cmap
                if cmap is None and shade:
                    i1, i2, i3 = 0, int(len(ps2)/3), int(2*len(ps2)/3)
                    v1[which_pt] = np.array(ps2[i1]) - np.array(ps2[i2])
                    v2[which_pt] = np.array(ps2[i2]) - np.array(ps2[i3])
                    which_pt += 1
        if cmap is None and shade:
            normals = np.cross(v1, v2)
        else :
            normals = []

        polyc = art3d.Poly3DCollection(polys, *args, **kwargs)

        if fcolors is not None:
            if shade:
                colset = self._shade_colors(colset, normals)
            polyc.set_facecolors(colset)
            polyc.set_edgecolors(colset)
        elif cmap:
            colset = np.array(colset)
            polyc.set_array(colset)
            if vmin is not None or vmax is not None:
                polyc.set_clim(vmin, vmax)
            if norm is not None:
                polyc.set_norm(norm)
        else:
            if shade:
                colset = self._shade_colors(color, normals)
            else:
                colset = color
            polyc.set_facecolors(colset)

        self.add_collection(polyc)
        self.auto_scale_xyz(X, Y, Z, had_data)

        return polyc
コード例 #55
0
def hist2d(x,
           y,
           bins=20,
           range=None,
           weights=None,
           levels=None,
           smooth=None,
           ax=None,
           color=None,
           quiet=False,
           plot_datapoints=True,
           plot_density=True,
           plot_contours=True,
           no_fill_contours=False,
           fill_contours=False,
           contour_kwargs=None,
           contourf_kwargs=None,
           data_kwargs=None,
           **kwargs):
    """
    Plot a 2-D histogram of samples.

    Parameters
    ----------
    x : array_like[nsamples,]
       The samples.

    y : array_like[nsamples,]
       The samples.

    quiet : bool
        If true, suppress warnings for small datasets.

    levels : array_like
        The contour levels to draw.

    ax : matplotlib.Axes
        A axes instance on which to add the 2-D histogram.

    plot_datapoints : bool
        Draw the individual data points.

    plot_density : bool
        Draw the density colormap.

    plot_contours : bool
        Draw the contours.

    no_fill_contours : bool
        Add no filling at all to the contours (unlike setting
        ``fill_contours=False``, which still adds a white fill at the densest
        points).

    fill_contours : bool
        Fill the contours.

    contour_kwargs : dict
        Any additional keyword arguments to pass to the `contour` method.

    contourf_kwargs : dict
        Any additional keyword arguments to pass to the `contourf` method.

    data_kwargs : dict
        Any additional keyword arguments to pass to the `plot` method when
        adding the individual data points.

    """
    if ax is None:
        ax = pl.gca()

    # Set the default range based on the data range if not provided.
    if range is None:
        if "extent" in kwargs:
            logging.warn("Deprecated keyword argument 'extent'. "
                         "Use 'range' instead.")
            range = kwargs["extent"]
        else:
            range = [[x.min(), x.max()], [y.min(), y.max()]]

    # Set up the default plotting arguments.
    if color is None:
        color = "k"

    # Choose the default "sigma" contour levels.
    if levels is None:
        levels = 1.0 - np.exp(-0.5 * np.arange(0.5, 2.1, 0.5)**2)

    # This is the color map for the density plot, over-plotted to indicate the
    # density of the points near the center.
    density_cmap = LinearSegmentedColormap.from_list("density_cmap",
                                                     [color, (1, 1, 1, 0)])

    # This color map is used to hide the points at the high density areas.
    white_cmap = LinearSegmentedColormap.from_list("white_cmap", [(1, 1, 1),
                                                                  (1, 1, 1)],
                                                   N=2)

    # This "color map" is the list of colors for the contour levels if the
    # contours are filled.
    rgba_color = colorConverter.to_rgba(color)
    contour_cmap = [list(rgba_color) for l in levels] + [rgba_color]
    for i, l in enumerate(levels):
        contour_cmap[i][-1] *= float(i) / (len(levels) + 1)

    # We'll make the 2D histogram to directly estimate the density.
    try:
        H, X, Y = np.histogram2d(x.flatten(),
                                 y.flatten(),
                                 bins=bins,
                                 range=list(map(np.sort, range)),
                                 weights=weights)
    except ValueError:
        raise ValueError("It looks like at least one of your sample columns "
                         "have no dynamic range. You could try using the "
                         "'range' argument.")

    if smooth is not None:
        if gaussian_filter is None:
            raise ImportError("Please install scipy for smoothing")
        H = gaussian_filter(H, smooth)

    if plot_contours or plot_density:
        # Compute the density levels.
        Hflat = H.flatten()
        inds = np.argsort(Hflat)[::-1]
        Hflat = Hflat[inds]
        sm = np.cumsum(Hflat)
        sm /= sm[-1]
        V = np.empty(len(levels))
        for i, v0 in enumerate(levels):
            try:
                V[i] = Hflat[sm <= v0][-1]
            except:
                V[i] = Hflat[0]
        V.sort()
        m = np.diff(V) == 0
        if np.any(m) and not quiet:
            logging.warning("Too few points to create valid contours")
        while np.any(m):
            V[np.where(m)[0][0]] *= 1.0 - 1e-4
            m = np.diff(V) == 0
        V.sort()

        # Compute the bin centers.
        X1, Y1 = 0.5 * (X[1:] + X[:-1]), 0.5 * (Y[1:] + Y[:-1])

        # Extend the array for the sake of the contours at the plot edges.
        H2 = H.min() + np.zeros((H.shape[0] + 4, H.shape[1] + 4))
        H2[2:-2, 2:-2] = H
        H2[2:-2, 1] = H[:, 0]
        H2[2:-2, -2] = H[:, -1]
        H2[1, 2:-2] = H[0]
        H2[-2, 2:-2] = H[-1]
        H2[1, 1] = H[0, 0]
        H2[1, -2] = H[0, -1]
        H2[-2, 1] = H[-1, 0]
        H2[-2, -2] = H[-1, -1]
        X2 = np.concatenate([
            X1[0] + np.array([-2, -1]) * np.diff(X1[:2]),
            X1,
            X1[-1] + np.array([1, 2]) * np.diff(X1[-2:]),
        ])
        Y2 = np.concatenate([
            Y1[0] + np.array([-2, -1]) * np.diff(Y1[:2]),
            Y1,
            Y1[-1] + np.array([1, 2]) * np.diff(Y1[-2:]),
        ])

    if plot_datapoints:
        if data_kwargs is None:
            data_kwargs = dict()
        data_kwargs["color"] = data_kwargs.get("color", color)
        data_kwargs["ms"] = data_kwargs.get("ms", 2.0)
        data_kwargs["mec"] = data_kwargs.get("mec", "none")
        data_kwargs["alpha"] = data_kwargs.get("alpha", 0.1)
        ax.plot(x, y, "o", zorder=-1, rasterized=True, **data_kwargs)

    # Plot the base fill to hide the densest data points.
    if (plot_contours or plot_density) and not no_fill_contours:
        ax.contourf(X2,
                    Y2,
                    H2.T, [V.min(), H.max()],
                    cmap=white_cmap,
                    antialiased=False)

    if plot_contours and fill_contours:
        if contourf_kwargs is None:
            contourf_kwargs = dict()
        contourf_kwargs["colors"] = contourf_kwargs.get("colors", contour_cmap)
        contourf_kwargs["antialiased"] = contourf_kwargs.get(
            "antialiased", False)
        ax.contourf(X2, Y2, H2.T,
                    np.concatenate([[0], V, [H.max() * (1 + 1e-4)]]),
                    **contourf_kwargs)

    # Plot the density map. This can't be plotted at the same time as the
    # contour fills.
    elif plot_density:
        ax.pcolor(X, Y, H.max() - H.T, cmap=density_cmap)

    # Plot the contour edge colors.
    if plot_contours:
        if contour_kwargs is None:
            contour_kwargs = dict()
        contour_kwargs["colors"] = contour_kwargs.get("colors", color)
        ax.contour(X2, Y2, H2.T, V, **contour_kwargs)

    ax.set_xlim(range[0])
    ax.set_ylim(range[1])
コード例 #56
0
        q = args.q
        I = args.I
        sigq = args.sigq

        f = plt.figure(figsize=[6,6])
        gs = gridspec.GridSpec(2, 1, height_ratios=[3,1])

        ax0 = plt.subplot(gs[0])
        #handle sigq values whose error bounds would go negative and be missing on the log scale
        #sigq2 = np.copy(sigq)
        #sigq2[sigq>I] = I[sigq>I]*.999
        sigq2 = np.interp(qraw, q, sigq)
        sigq2[sigq2>Iraw] = Iraw[sigq2>Iraw]*.999
        #ax0.errorbar(q, I, fmt='k-', yerr=[sigq2[q<=q[-1]],sigq[q<=q[-1]]], capsize=0, elinewidth=0.1, ecolor=cc.to_rgba('0',alpha=0.5),label='Supplied Data')
        #ax0.plot(q, I, 'k.',alpha=0.1,mec='none',label='Raw Data')
        ax0.errorbar(qraw, Iraw, fmt='k.', yerr=sigq2, mec='none', mew=0, ms=3, alpha=0.3, capsize=0, elinewidth=0.1, ecolor=cc.to_rgba('0',alpha=0.5),label='Supplied Data')
        ax0.plot(q, I, 'k--',alpha=0.7,lw=1,label='Supplied Fit')
        ax0.plot(qdata[qdata<=q[-1]], Idata[qdata<=q[-1]], 'bo',alpha=0.5,label='Interpolated')
        ax0.plot(qbinsc[qdata<=q[-1]],Imean[qdata<=q[-1]],'r.',label='DENSS Map')
        handles,labels = ax0.get_legend_handles_labels()
        handles = [handles[3], handles[0], handles[1],handles[2]]
        labels = [labels[3], labels[0], labels[1], labels[2]]
        xmax = np.min([qraw.max(),q.max(),qdata.max()])*1.1
        ymin = np.min([np.min(I[q<=xmax]),np.min(Idata[qdata<=xmax]),np.min(Imean[qdata<=xmax])])
        ymax = np.max([np.max(I[q<=xmax]),np.max(Idata[qdata<=xmax]),np.max(Imean[qdata<=xmax])])
        ax0.set_xlim([-xmax*.05,xmax])
        ax0.set_ylim([0.5*ymin,1.5*ymax])
        ax0.legend(handles,labels)
        ax0.semilogy()
        ax0.set_ylabel('I(q)')
コード例 #57
0
npts = 100

# Make some spirals
r = N.array(range(nverts))
theta = N.array(range(nverts)) * (2*N.pi)/(nverts-1)
xx = r * N.sin(theta)
yy = r * N.cos(theta)
spiral = zip(xx,yy)

# Make some offsets
xo = N.random.randn(npts)
yo = N.random.randn(npts)
xyo = zip(xo, yo)

# Make a list of colors cycling through the rgbcmyk series.
colors = [colorConverter.to_rgba(c) for c in ('r','g','b','c','y','m','k')]

fig = P.figure()

a = fig.add_subplot(2,2,1)
col = collections.LineCollection([spiral], offsets=xyo,
                                transOffset=a.transData)
trans = transforms.Affine2D().scale(fig.dpi/72.0)
col.set_transform(trans)  # the points to pixels transform
    # Note: the first argument to the collection initializer
    # must be a list of sequences of x,y tuples; we have only
    # one sequence, but we still have to put it in a list.
a.add_collection(col, autolim=True)
    # autolim=True enables autoscaling.  For collections with
    # offsets like this, it is neither efficient nor accurate,
    # but it is good enough to generate a plot that you can use
コード例 #58
0
def cc(arg):
    return colorConverter.to_rgba(arg, alpha=0.6)
コード例 #59
0
def draw_networkx_edges(G, pos,
                        edgelist=None,
                        width=1.0,
                        edge_color='k',
                        style='solid',
                        alpha=None,
                        edge_cmap=None,
                        edge_vmin=None,
                        edge_vmax=None, 
                        ax=None,
                        arrows=True,
                        **kwds):
    """Draw the edges of the graph G

    This draws only the edges of the graph G.

    pos is a dictionary keyed by vertex with a two-tuple
    of x-y positions as the value.
    See networkx.layout for functions that compute node positions.

    edgelist is an optional list of the edges in G to be drawn.
    If provided, only the edges in edgelist will be drawn. 

    edgecolor can be a list of matplotlib color letters such as 'k' or
    'b' that lists the color of each edge; the list must be ordered in
    the same way as the edge list. Alternatively, this list can contain
    numbers and those number are mapped to a color scale using the color
    map edge_cmap.  Finally, it can also be a list of (r,g,b) or (r,g,b,a)
    tuples, in which case these will be used directly to color the edges.  If
    the latter mode is used, you should not provide a value for alpha, as it
    would be applied globally to all lines.
    
    For directed graphs, "arrows" (actually just thicker stubs) are drawn
    at the head end.  Arrows can be turned off with keyword arrows=False.

    See draw_networkx for the list of other optional parameters.

    """
    try:
        import matplotlib
        import matplotlib.pylab as pylab
        import matplotlib.cbook as cb
        from matplotlib.colors import colorConverter,Colormap
        from matplotlib.collections import LineCollection
        import numpy
    except ImportError:
        raise ImportError, "Matplotlib required for draw()"
    except RuntimeError:
        pass # unable to open display

    if ax is None:
        ax=pylab.gca()

    if edgelist is None:
        edgelist=G.edges()

    if not edgelist or len(edgelist)==0: # no edges!
        return None

    # set edge positions
    edge_pos=numpy.asarray([(pos[e[0]],pos[e[1]]) for e in edgelist])
    
    if not cb.iterable(width):
        lw = (width,)
    else:
        lw = width

    if not cb.is_string_like(edge_color) \
           and cb.iterable(edge_color) \
           and len(edge_color)==len(edge_pos):
        if numpy.alltrue([cb.is_string_like(c) 
                         for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
            edge_colors = tuple([colorConverter.to_rgba(c,alpha) 
                                 for c in edge_color])
        elif numpy.alltrue([not cb.is_string_like(c) 
                           for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
            if numpy.alltrue([cb.iterable(c) and len(c) in (3,4)
                             for c in edge_color]):
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
            raise ValueError('edge_color must consist of either color names or numbers')
    else:
        if len(edge_color)==1:
            edge_colors = ( colorConverter.to_rgba(edge_color, alpha), )
        else:
            raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges')

    edge_collection = LineCollection(edge_pos,
                                     colors       = edge_colors,
                                     linewidths   = lw,
                                     antialiaseds = (1,),
                                     linestyle    = style,     
                                     transOffset = ax.transData,             
                                     )

    # Note: there was a bug in mpl regarding the handling of alpha values for
    # each line in a LineCollection.  It was fixed in matplotlib in r7184 and
    # r7189 (June 6 2009).  We should then not set the alpha value globally,
    # since the user can instead provide per-edge alphas now.  Only set it
    # globally if provided as a scalar.
    if cb.is_numlike(alpha):
        edge_collection.set_alpha(alpha)

    # need 0.87.7 or greater for edge colormaps
    mpl_version=matplotlib.__version__
    if mpl_version.endswith('svn'):
        mpl_version=matplotlib.__version__[0:-3]
    if mpl_version.endswith('pre'):
        mpl_version=matplotlib.__version__[0:-3]
    if map(int,mpl_version.split('.'))>=[0,87,7]:
        if edge_colors is None:
            if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap))
            edge_collection.set_array(numpy.asarray(edge_color))
            edge_collection.set_cmap(edge_cmap)
            if edge_vmin is not None or edge_vmax is not None:
                edge_collection.set_clim(edge_vmin, edge_vmax)
            else:
                edge_collection.autoscale()
            pylab.sci(edge_collection)

#    else:
#        sys.stderr.write(\
#            """matplotlib version >= 0.87.7 required for colormapped edges.
#        (version %s detected)."""%matplotlib.__version__)
#        raise UserWarning(\
#            """matplotlib version >= 0.87.7 required for colormapped edges.
#        (version %s detected)."""%matplotlib.__version__)

    arrow_collection=None

    if G.is_directed() and arrows:

        # a directed graph hack
        # draw thick line segments at head end of edge
        # waiting for someone else to implement arrows that will work 
        arrow_colors = ( colorConverter.to_rgba('k', alpha), )
        a_pos=[]
        p=1.0-0.25 # make head segment 25 percent of edge length
        for src,dst in edge_pos:
            x1,y1=src
            x2,y2=dst
            dx=x2-x1 # x offset
            dy=y2-y1 # y offset
            d=numpy.sqrt(float(dx**2+dy**2)) # length of edge
            if d==0: # source and target at same position
                continue
            if dx==0: # vertical edge
                xa=x2
                ya=dy*p+y1
            if dy==0: # horizontal edge
                ya=y2
                xa=dx*p+x1
            else:
                theta=numpy.arctan2(dy,dx)
                xa=p*d*numpy.cos(theta)+x1
                ya=p*d*numpy.sin(theta)+y1
                
            a_pos.append(((xa,ya),(x2,y2)))

        arrow_collection = LineCollection(a_pos,
                                colors       = arrow_colors,
                                linewidths   = [4*ww for ww in lw],
                                antialiaseds = (1,),
                                transOffset = ax.transData,             
                                )
        
    # update view        
    minx = numpy.amin(numpy.ravel(edge_pos[:,:,0]))
    maxx = numpy.amax(numpy.ravel(edge_pos[:,:,0]))
    miny = numpy.amin(numpy.ravel(edge_pos[:,:,1]))
    maxy = numpy.amax(numpy.ravel(edge_pos[:,:,1]))

    w = maxx-minx
    h = maxy-miny
    padx, pady = 0.05*w, 0.05*h
    corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady)
    ax.update_datalim( corners)
    ax.autoscale_view()

    edge_collection.set_zorder(1) # edges go behind nodes            
    ax.add_collection(edge_collection)
    if arrow_collection:
        arrow_collection.set_zorder(1) # edges go behind nodes            
        ax.add_collection(arrow_collection)

    return edge_collection
コード例 #60
0
def index_bar(
    ax,
    vals,
    facecolor='b',
    edgecolor='l',
    width=4,
    alpha=1.0,
):
    """Add a bar collection graph with height vals (-1 is missing).

    Parameters
    ----------
    ax : `Axes`
        an Axes instance to plot to
    vals : sequence
        a sequence of values
    facecolor : color
        the color of the bar face
    edgecolor : color
        the color of the bar edges
    width : int
        the bar width in points
    alpha : float
       bar transparency

    Returns
    -------
    ret : `barCollection`
        The `barrCollection` added to the axes

    """

    facecolors = (colorConverter.to_rgba(facecolor, alpha), )
    edgecolors = (colorConverter.to_rgba(edgecolor, alpha), )

    right = width / 2.0
    left = -width / 2.0

    bars = [((left, 0), (left, v), (right, v), (right, 0)) for v in vals
            if v != -1]

    sx = ax.figure.dpi * (1.0 / 72.0)  # scale for points
    sy = ax.bbox.height / ax.viewLim.height

    barTransform = Affine2D().scale(sx, sy)

    offsetsBars = [(i, 0) for i, v in enumerate(vals) if v != -1]

    barCollection = PolyCollection(
        bars,
        facecolors=facecolors,
        edgecolors=edgecolors,
        antialiaseds=(0, ),
        linewidths=(0.5, ),
        offsets=offsetsBars,
        transOffset=ax.transData,
    )
    barCollection.set_transform(barTransform)

    minpy, maxx = (0, len(offsetsBars))
    miny = 0
    maxy = max([v for v in vals if v != -1])
    corners = (minpy, miny), (maxx, maxy)
    ax.update_datalim(corners)
    ax.autoscale_view()

    # add these last
    ax.add_collection(barCollection)
    return barCollection