Demonstrate how to create a plot class to plot multiple meshes while
    adding scalars and text.

    Plot two ants and airplane
170653
def plot_ants_plane(off_screen=False, notebook=None):
    

    # load and shrink airplane
    airplane = vtki.PolyData(planefile)
    airplane.points /= 10
    # pts = airplane.points # gets pointer to array
    # pts /= 10  # shrink

    # rotate and translate ant so it is on the plane
    ant = vtki.PolyData(antfile)
    ant.rotate_x(90)
    ant.translate([90, 60, 15])

    # Make a copy and add another ant
    ant_copy = ant.copy()
    ant_copy.translate([30, 0, -10])

    # Create plotting object
    plotter = vtki.Plotter(off_screen=off_screen, notebook=notebook)
    plotter.add_mesh(ant, 'r')
    plotter.add_mesh(ant_copy, 'b')

    # Add airplane mesh and make the color equal to the Y position
    plane_scalars = airplane.points[:, 1]
    plotter.add_mesh(airplane, scalars=plane_scalars, stitle='Plane Y\nLocation')
    plotter.add_text('Ants and Plane Example')
    plotter.plot()
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
1147298
def show_multi(func:Callable[[int,int],Image], r:int=1, c:int=1, figsize:Tuple=(9,9)):
    ""
    plot_multi(lambda i,j,ax: func(i,j).show(ax), r, c, figsize=figsize)
60821
def plot(ID, pipeline='everest2', show=True, campaign=None):
    '''
    

    '''

    # Get the data
    time, flux = get(ID, pipeline=pipeline, campaign=campaign)

    # Remove nans
    mask = np.where(np.isnan(flux))[0]
    time = np.delete(time, mask)
    flux = np.delete(flux, mask)

    # Plot it
    fig, ax = pl.subplots(1, figsize=(10, 4))
    fig.subplots_adjust(bottom=0.15)
    ax.plot(time, flux, "k.", markersize=3, alpha=0.5)

    # Axis limits
    N = int(0.995 * len(flux))
    hi, lo = flux[np.argsort(flux)][[N, -N]]
    pad = (hi - lo) * 0.1
    ylim = (lo - pad, hi + pad)
    ax.set_ylim(ylim)

    # Show the CDPP
    from .k2 import CDPP
    ax.annotate('%.2f ppm' % CDPP(flux),
                xy=(0.98, 0.975), xycoords='axes fraction',
                ha='right', va='top', fontsize=12, color='r', zorder=99)

    # Appearance
    ax.margins(0, None)
    ax.set_xlabel("Time (BJD - 2454833)", fontsize=16)
    ax.set_ylabel("%s Flux" % pipeline.upper(), fontsize=16)
    fig.canvas.set_window_title("%s: EPIC %d" % (pipeline.upper(), ID))

    if show:
        pl.show()
        pl.close()
    else:
        return fig, ax
1302756
def plot3D_stacktriax(initial,final_t,N_MAT,file_output):
    

    # Setup Stackel potential
    TT = pot.stackel_triax()
    times = choose_NT(N_MAT)
    timeseries=np.linspace(0.,final_t,times)
    # Integrate orbit
    results = odeint(pot.orbit_derivs2,initial,timeseries,args=(TT,),rtol=1e-13,atol=1e-13)
    # Find actions, angles and frequencies
    (act,ang,n_vec,toy_aa, pars),loop = find_actions(results, timeseries,N_matrix=N_MAT,ifloop=True)

    toy_pot = 0
    if(loop[2]>0.5 or loop[0]>0.5):
        toy_pot = pot.isochrone(par=np.append(pars,0.))
    else:
        toy_pot = pot.harmonic_oscillator(omega=pars[:3])
    # Integrate initial condition in toy potential
    timeseries_2=np.linspace(0.,2.*final_t,3500)
    results_toy = odeint(pot.orbit_derivs2,initial,timeseries_2,args=(toy_pot,))

    # and plot
    f,a = plt.subplots(2,3,figsize=[3.32,5.5])
    a[0,0] = plt.subplot2grid((3,2), (0, 0))
    a[1,0] = plt.subplot2grid((3,2), (0, 1))
    a[0,1] = plt.subplot2grid((3,2), (1, 0))
    a[1,1] = plt.subplot2grid((3,2), (1, 1))
    a[0,2] = plt.subplot2grid((3,2), (2, 0),colspan=2)
    plt.subplots_adjust(wspace=0.5,hspace=0.45)

    # xy orbit
    a[0,0].plot(results.T[0],results.T[1],'k')
    a[0,0].set_xlabel(r'$x/{\rm kpc}$')
    a[0,0].set_ylabel(r'$y/{\rm kpc}$')
    a[0,0].xaxis.set_major_locator(MaxNLocator(5))
    # xz orbit
    a[1,0].plot(results.T[0],results.T[2],'k')
    a[1,0].set_xlabel(r'$x/{\rm kpc}$')
    a[1,0].set_ylabel(r'$z/{\rm kpc}$')
    a[1,0].xaxis.set_major_locator(MaxNLocator(5))
    # toy orbits
    a[0,0].plot(results_toy.T[0],results_toy.T[1],'r',alpha=0.2,linewidth=0.3)
    a[1,0].plot(results_toy.T[0],results_toy.T[2],'r',alpha=0.2,linewidth=0.3)

    # Toy actions
    a[0,2].plot(Conv*timeseries,toy_aa.T[0],'k:',label='Toy action')
    a[0,2].plot(Conv*timeseries,toy_aa.T[1],'r:')
    a[0,2].plot(Conv*timeseries,toy_aa.T[2],'b:')
    # Arrows to show approx. actions
    arrow_end = a[0,2].get_xlim()[1]
    arrowd = 0.08*(arrow_end-a[0,2].get_xlim()[0])
    a[0,2].annotate('',(arrow_end+arrowd,act[0]),(arrow_end,act[0]),arrowprops=dict(arrowstyle='<-',color='k'),annotation_clip=False)
    a[0,2].annotate('',(arrow_end+arrowd,act[1]),(arrow_end,act[1]),arrowprops=dict(arrowstyle='<-',color='r'),annotation_clip=False)
    a[0,2].annotate('',(arrow_end+arrowd,act[2]),(arrow_end,act[2]),arrowprops=dict(arrowstyle='<-',color='b'),annotation_clip=False)
    # True actions
    a[0,2].plot(Conv*timeseries,TT.action(results[0])[0]*np.ones(len(timeseries)),'k',label='True action')
    a[0,2].plot(Conv*timeseries,TT.action(results[0])[1]*np.ones(len(timeseries)),'k')
    a[0,2].plot(Conv*timeseries,TT.action(results[0])[2]*np.ones(len(timeseries)),'k')
    a[0,2].set_xlabel(r'$t/{\rm Gyr}$')
    a[0,2].set_ylabel(r'$J/{\rm kpc\,km\,s}^{-1}$')
    leg = a[0,2].legend(loc='upper center',bbox_to_anchor=(0.5,1.2),ncol=3, numpoints = 1)
    leg.draw_frame(False)

    # Toy angle coverage
    a[0,1].plot(toy_aa.T[3]/(np.pi),toy_aa.T[4]/(np.pi),'k.',markersize=0.4)
    a[0,1].set_xlabel(r'$\theta_1/\pi$')
    a[0,1].set_ylabel(r'$\theta_2/\pi$')
    a[1,1].plot(toy_aa.T[3]/(np.pi),toy_aa.T[5]/(np.pi),'k.',markersize=0.4)
    a[1,1].set_xlabel(r'$\theta_1/\pi$')
    a[1,1].set_ylabel(r'$\theta_3/\pi$')

    plt.savefig(file_output,bbox_inches='tight')
    return act
1285875
def plot_multi(func:Callable[[int,int,plt.Axes],None], r:int=1, c:int=1, figsize:Tuple=(12,6)):
    ""
    axes = plt.subplots(r, c, figsize=figsize)[1]
    for i in range(r):
        for j in range(c): func(i,j,axes[i,j])
830796
def create_scree_plot(data, o_filename, options):
    
    # Importing plt
    mpl.use("Agg")
    import matplotlib.pyplot as plt
    plt.ioff()

    # Computing the cumulative sum
    cumul_data = np.cumsum(data)

    # Creating the figure and axes
    fig, axes = plt.subplots(2, 1, figsize=(8, 16))

    # The title of the figure
    fig.suptitle(options.scree_plot_title, fontsize=16, weight="bold")

    fig.subplots_adjust(hspace=0.27, top=0.93, bottom=0.06)

    # Modifying the spines
    for axe in axes:
        axe.xaxis.set_ticks_position("bottom")
        axe.yaxis.set_ticks_position("left")
        axe.spines["top"].set_visible(False)
        axe.spines["right"].set_visible(False)
        axe.spines["left"].set_position(("outward", 9))
        axe.spines["bottom"].set_position(("outward", 9))

    # First, plotting the eigenvalues
    axes[0].set_title("Scree Plot", weight="bold")
    axes[0].set_xlabel("Component")
    axes[0].set_ylabel("Eigenvalue")
    axes[0].plot(np.arange(len(data)) + 1, data, marker="o", c="#0099CC",
                 mec="#0099CC", ls="-", lw=2, clip_on=False)

    # Then, plotting the annotation
    for i in range(len(data)):
        axes[0].annotate(np.round(data[i], 3),
                         xy=(np.arange(len(data))[i] + 1, data[i]),
                         xytext=(1, 10), textcoords="offset points",
                         ha="left", va="bottom",
                         bbox=dict(boxstyle="round,pad=0.5", fc="#FFFFFF"))

    # Next plot the cumulative values
    axes[1].set_title(("Cumulative explained variance "
                       "(max={:.3f})".format(np.sum(data))), weight="bold")
    axes[1].set_xlabel("Component")
    axes[1].set_ylabel("Cumulative explained variance")
    axes[1].axhline(np.sum(data) * 0.8, ls="--", lw="2", c="#999999")
    axes[1].plot(np.arange(len(data)) + 1, cumul_data, marker="o", c="#CC0000",
                 mec="#CC0000", mfc="#CC0000", ls="-", lw=2, clip_on=False)

    # Then, plotting the annotation
    for i in range(len(data)):
        axes[1].annotate(np.round(cumul_data[i], 3),
                         xy=(np.arange(len(data))[i] + 1, cumul_data[i]),
                         xytext=(1, -10), textcoords="offset points",
                         ha="left", va="top",
                         bbox=dict(boxstyle="round,pad=0.5", fc="#FFFFFF"))

    # Saving the file
    plt.savefig(o_filename, dpi=300)
    plt.close(fig)
177177
def plot_heatmap(fig, ax, data,
                 xaxislabel=None, yaxislabel=None,
                 xticklabels=None, yticklabels=None,
                 title=None, grid=True,
                 values_in_cells=True, round_values_in_cells=2,
                 legend=False,
                 fontsize_axislabel=None,
                 fontsize_axisticks=None,
                 fontsize_cell_values=None):
    "

    if not isinstance(data, np.ndarray):
        data = np.array(data)

    if data.ndim != 2:
        raise ValueError('`data` must be a 2D matrix/array')

    # draw basic heatmap
    cax = ax.matshow(data)

    # draw legend
    if legend:
        fig.colorbar(cax)

    # set title
    if title:
        ax.set_title(title, y=1.25)

    n_rows, n_cols = data.shape

    # draw values in cells
    if values_in_cells:
        textcol_thresh = data.min() + (data.max() - data.min()) / 2
        x_indices, y_indices = np.meshgrid(np.arange(n_cols), np.arange(n_rows))
        for x, y in zip(x_indices.flatten(), y_indices.flatten()):
            val = data[y, x]
            # lower values get white text color for better visibility
            textcol = 'white' if val < textcol_thresh else 'black'
            disp_val = round(val, round_values_in_cells) if round_values_in_cells is not None else val
            ax.text(x, y, disp_val, va='center', ha='center', color=textcol, fontsize=fontsize_cell_values)

    # customize axes
    if xaxislabel:
        ax.set_xlabel(xaxislabel)
    if yaxislabel:
        ax.set_ylabel(yaxislabel)

    if fontsize_axislabel:
        for item in (ax.xaxis.label, ax.yaxis.label):
            item.set_fontsize(fontsize_axislabel)

    ax.set_xticks(np.arange(0, n_cols))
    ax.set_yticks(np.arange(0, n_rows))

    if xticklabels is not None:
        ax.set_xticklabels(xticklabels, rotation=45, ha='left')
    if yticklabels is not None:
        ax.set_yticklabels(yticklabels)

    if fontsize_axisticks:
        for label in (ax.get_xticklabels() + ax.get_yticklabels()):
            label.set_fontsize(fontsize_axisticks)

    # gridlines based on minor ticks
    if grid:
        ax.set_xticks(np.arange(-.5, n_cols), minor=True)
        ax.set_yticks(np.arange(-.5, n_rows), minor=True)
        ax.grid(which='minor', color='w', linestyle='-', linewidth=1)

    return fig, ax
948803
def grid_2d_8graph(self, m, n):
        """"""
        me = nx.Graph()
        node = me.node
        add_node = me.add_node
        add_edge = me.add_edge
        for i in range(m):
            for j in range(n):
                add_node((i, j))
                if i > 0:
                    add_edge((i, j), (i-1, j))
                    if j > 0:
                        add_edge((i, j), (i-1, j-1))
                if j > 0:
                    add_edge((i, j), (i, j-1))
                if (i - 1, j + 1) in node:
                    add_edge((i, j), (i-1, j+1))
        return self.copy_from(me)
588836
def create_singleplots(plotman, cov, mag, pha, pha_fpi, alpha, options):
    '''
    '''
    magunit = 'log_rho'
    if not pha == []:
        [real, imag] = calc_complex(mag, pha)
        if not pha_fpi == []:
            [real_fpi, imag_fpi] = calc_complex(mag, pha_fpi)
            if options.cmaglin:
                mag = np.power(10, mag)
                magunit = 'rho'
            data = np.column_stack((mag, cov, pha, real, imag,
                                    pha_fpi, real_fpi, imag_fpi))
            titles = ['Magnitude', 'Coverage',
                      'Phase', 'Real Part', 'Imaginary Part',
                      'FPI Phase', 'FPI Real Part', 'FPI Imaginary Part']
            unites = [
                magunit, 'cov',
                'phi', 'log_real', 'log_imag',
                'phi', 'log_real', 'log_imag'
            ]
            vmins = [options.mag_vmin, options.cov_vmin,
                     options.pha_vmin, options.real_vmin, options.imag_vmin,
                     options.pha_vmin, options.real_vmin, options.imag_vmin]
            vmaxs = [options.mag_vmax, options.cov_vmax,
                     options.pha_vmax, options.real_vmax, options.imag_vmax,
                     options.pha_vmax, options.real_vmax, options.imag_vmax]
            cmaps = ['jet', 'GnBu',
                     'jet_r', 'jet_r', 'plasma_r',
                     'plasma', 'jet_r', 'plasma_r']
            saves = ['rho', 'cov',
                     'phi', 'real', 'imag',
                     'fpi_phi', 'fpi_real', 'fpi_imag']
        else:
            if options.cmaglin:
                mag = np.power(10, mag)
                magunit = 'rho'
            data = np.column_stack((mag, cov, pha, real, imag))
            titles = ['Magnitude', 'Coverage',
                      'Phase', 'Real Part', 'Imaginary Part']
            unites = [magunit, 'cov',
                      'phi', 'log_real', 'log_imag']
            vmins = [options.mag_vmin, options.cov_vmin,
                     options.pha_vmin, options.real_vmin, options.imag_vmin]
            vmaxs = [options.mag_vmax, options.cov_vmax,
                     options.pha_vmax, options.real_vmax, options.imag_vmax]
            cmaps = ['jet', 'GnBu',
                     'jet_r', 'jet_r', 'plasma_r']
            saves = ['rho', 'cov',
                     'phi', 'real', 'imag']
    else:
        data = np.column_stack((mag, cov))
        titles = ['Magnitude', 'Coverage']
        unites = [magunit, 'cov']
        vmins = [options.mag_vmin, options.cov_vmin]
        vmaxs = [options.mag_vmax, options.cov_vmax]
        cmaps = ['jet', 'GnBu']
        saves = ['rho', 'cov']
    try:
        mod_rho = np.genfromtxt('rho/rho.dat', skip_header=1, usecols=([0]))
        mod_pha = np.genfromtxt('rho/rho.dat', skip_header=1, usecols=([1]))
        data = np.column_stack((data, mod_rho, mod_pha))
        titles.append('Model')
        titles.append('Model')
        unites.append('rho')
        unites.append('phi')
        vmins.append(options.mag_vmin)
        vmins.append(options.pha_vmin)
        vmaxs.append(options.mag_vmax)
        vmaxs.append(options.pha_vmax)
        cmaps.append('jet')
        cmaps.append('plasma')
        saves.append('rhomod')
        saves.append('phamod')
    except:
        pass
    for datum, title, unit, vmin, vmax, cm, save in zip(
            np.transpose(data), titles, unites, vmins, vmaxs, cmaps, saves):
        sizex, sizez = getfigsize(plotman)
        f, ax = plt.subplots(1, figsize=(sizex, sizez))
        cid = plotman.parman.add_data(datum)
        # handle options
        cblabel = units.get_label(unit)
        if options.title is not None:
            title = options.title
        zlabel = 'z [' + options.unit + ']'
        xlabel = 'x [' + options.unit + ']'
        xmin, xmax, zmin, zmax, vmin, vmax = check_minmax(
                plotman,
                cid,
                options.xmin, options.xmax,
                options.zmin, options.zmax,
                vmin, vmax
                )
        # plot
        cmap = mpl_cm.get_cmap(cm)
        fig, ax, cnorm, cmap, cb, scalarMap = plotman.plot_elements_to_ax(
                cid=cid,
                cid_alpha=alpha,
                ax=ax,
                xmin=xmin,
                xmax=xmax,
                zmin=zmin,
                zmax=zmax,
                cblabel=cblabel,
                title=title,
                zlabel=zlabel,
                xlabel=xlabel,
                plot_colorbar=True,
                cmap_name=cm,
                over=cmap(1.0),
            under=cmap(0.0),
                no_elecs=options.no_elecs,
                cbmin=vmin,
                cbmax=vmax,
                )
        f.tight_layout()
        f.savefig(save + '.png', dpi=300)
671366
def MeshArrows(*inputobj, **options):
    
    s = options.pop("s", None)
    scale = options.pop("scale", 1)
    c = options.pop("c", "gray")
    alpha = options.pop("alpha", 1)
    res = options.pop("res", 12)

    mesh, u = _inputsort(inputobj)
    startPoints = mesh.coordinates()
    u_values = np.array([u(p) for p in mesh.coordinates()])
    if not utils.isSequence(u_values[0]):
        printc("~times Error: cannot show Arrows for 1D scalar values!", c=1)
        exit()
    endPoints = mesh.coordinates() + u_values
    if u_values.shape[1] == 2:  # u_values is 2D
        u_values = np.insert(u_values, 2, 0, axis=1)  # make it 3d
        startPoints = np.insert(startPoints, 2, 0, axis=1)  # make it 3d
        endPoints = np.insert(endPoints, 2, 0, axis=1)  # make it 3d

    actor = shapes.Arrows(
        startPoints, endPoints, s=s, scale=scale, c=c, alpha=alpha, res=res
    )
    actor.mesh = mesh
    actor.u = u
    actor.u_values = u_values
    return actor
435868
def plot_init(fignum, w, h):
    
    global fig_x_pos, fig_y_pos, plt_num
    dpi = 80
    if isServer:
        dpi = 240
    # plt.ion()
    plt_num += 1
    fig = plt.figure(num=fignum, figsize=(w, h), dpi=dpi)
    if (not isServer) and (not set_env.IS_NOTEBOOK):
        plt.get_current_fig_manager().show()
        # plt.get_current_fig_manager().window.wm_geometry('+%d+%d' %
        # (fig_x_pos,fig_y_pos)) # this only works with matplotlib.use('TKAgg')
        fig_x_pos = fig_x_pos + dpi * (w) + 25
        if plt_num == 3:
            plt_num = 0
            fig_x_pos = 25
            fig_y_pos = fig_y_pos + dpi * (h) + 25
        plt.figtext(.02, .01, version_num)
# plt.connect('button_press_event',click)
#
    # plt.ioff()
    return fig
236658
def mtdotplots(args):
    
    from jcvi.graphics.dotplot import check_beds, dotplot

    p = OptionParser(mtdotplots.__doc__)
    p.set_beds()
    opts, args, iopts = p.set_image_options(args, figsize="16x8", dpi=90)

    if len(args) != 3:
        sys.exit(not p.print_help())

    a, b, ac = args
    fig = plt.figure(1, (iopts.w, iopts.h))
    root = fig.add_axes([0, 0, 1, 1])
    r1 = fig.add_axes([0, 0, .5, 1])
    r2 = fig.add_axes([.5, 0, .5, 1])
    a1 = fig.add_axes([.05, .1, .4, .8])
    a2 = fig.add_axes([.55, .1, .4, .8])

    anchorfile = op.join(a, ac)
    qbed, sbed, qorder, sorder, is_self = check_beds(anchorfile, p, opts)
    dotplot(anchorfile, qbed, sbed, fig, r1, a1, is_self=is_self,
            genomenames="Mt3.5_Mt3.5")

    opts.qbed = opts.sbed = None
    anchorfile = op.join(b, ac)
    qbed, sbed, qorder, sorder, is_self = check_beds(anchorfile, p, opts)
    dotplot(anchorfile, qbed, sbed, fig, r2, a2, is_self=is_self,
            genomenames="Mt4.0_Mt4.0")

    root.text(.03, .95, "A", ha="center", va="center", size=36)
    root.text(.53, .95, "B", ha="center", va="center", size=36)

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    pf = "mtdotplots"
    image_name = pf + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
901275
def plot_cells(cell_1, cell_2, cell_3):
    """"""
    fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5))
    for ax in [ax1, ax2, ax3]:
        ax.grid(False)
        ax.set_xticks([])
        ax.set_yticks([])
    ax1.set_title("Type 1")
    ax1.imshow(cell_1)
    ax2.set_title("Type 2")
    ax2.imshow(cell_2)
    ax3.set_title("Type 3")
    ax3.imshow(cell_3)
    return ax1, ax2, ax3
589292
def plot_waves(self, ax=None, fontsize=12, **kwargs):
        
        ax, fig, plt = get_ax_fig_plt(ax)

        ax.grid(True)
        ax.set_xlabel("r [Bohr]")
        ax.set_ylabel(r"$r\phi,\, r\tilde\phi\, [Bohr]^{-\frac{1}{2}}$")

        #ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle="--")
        #ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1))

        for state, rfunc in self.pseudo_partial_waves.items():
            ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label="PS-WAVE: " + state)

        for state, rfunc in self.ae_partial_waves.items():
            ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label="AE-WAVE: " + state)

        ax.legend(loc="best", shadow=True, fontsize=fontsize)

        return fig
611681
def plot_network(
        self, state_sizes=None, state_scale=1.0, state_colors='#ff5500', state_labels='auto',
        arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%10.2f',
        max_width=12, max_height=12, figpadding=0.2, xticks=False, yticks=False, show_frame=False,
        **textkwargs):
        

        # Set the default values for the text dictionary
        from matplotlib import pyplot as _plt
        textkwargs.setdefault('size', None)
        textkwargs.setdefault('horizontalalignment', 'center')
        textkwargs.setdefault('verticalalignment', 'center')
        textkwargs.setdefault('color', 'black')
        # remove the temporary key 'arrow_label_size' as it cannot be parsed by plt.text!
        arrow_label_size = textkwargs.pop('arrow_label_size', textkwargs['size'])
        if self.pos is None:
            self.layout_automatic()
        # number of nodes
        n = len(self.pos)
        # get bounds and pad figure
        xmin = _np.min(self.pos[:, 0])
        xmax = _np.max(self.pos[:, 0])
        Dx = xmax - xmin
        xmin -= Dx * figpadding
        xmax += Dx * figpadding
        Dx *= 1 + figpadding
        ymin = _np.min(self.pos[:, 1])
        ymax = _np.max(self.pos[:, 1])
        Dy = ymax - ymin
        ymin -= Dy * figpadding
        ymax += Dy * figpadding
        Dy *= 1 + figpadding
        # sizes of nodes
        if state_sizes is None:
            state_sizes = 0.5 * state_scale * \
                min(Dx, Dy)**2 * _np.ones(n) / float(n)
        else:
            state_sizes = 0.5 * state_scale * \
                min(Dx, Dy)**2 * state_sizes / (_np.max(state_sizes) * float(n))
        # automatic arrow rescaling
        arrow_scale *= 1.0 / \
            (_np.max(self.A - _np.diag(_np.diag(self.A))) * _sqrt(n))
        # size figure
        if (Dx / max_width > Dy / max_height):
            figsize = (max_width, Dy * (max_width / Dx))
        else:
            figsize = (Dx / Dy * max_height, max_height)
        if self.ax is None:
            logger.debug("creating new figure")
            fig = _plt.figure(None, figsize=figsize)
            self.ax = fig.add_subplot(111)
        else:
            fig = self.ax.figure
            window_extend = self.ax.get_window_extent()
            axes_ratio = window_extend.height / window_extend.width
            data_ratio = (ymax - ymin) / (xmax - xmin)
            q = axes_ratio / data_ratio
            if q > 1.0:
                ymin *= q
                ymax *= q
            else:
                xmin /= q
                xmax /= q
        if not xticks:
            self.ax.get_xaxis().set_ticks([])
        if not yticks:
            self.ax.get_yaxis().set_ticks([])
        # show or suppress frame
        self.ax.set_frame_on(show_frame)
        # set node labels
        if state_labels is None:
            pass
        elif isinstance(state_labels, str) and state_labels == 'auto':
            state_labels = [str(i) for i in _np.arange(n)]
        else:
            if len(state_labels) != n:
                raise ValueError("length of state_labels({}) has to match length of states({})."
                                 .format(len(state_labels), n))
        # set node colors
        if state_colors is None:
            state_colors = '#ff5500'  # None is not acceptable
        if isinstance(state_colors, str):
            state_colors = [state_colors] * n
        if isinstance(state_colors, list) and not len(state_colors) == n:
            raise ValueError("Mistmatch between nstates and nr. state_colors (%u vs %u)" % (n, len(state_colors)))
        try:
            colorscales = _types.ensure_ndarray(state_colors, ndim=1, kind='numeric')
            colorscales /= colorscales.max()
            state_colors = [_plt.cm.binary(int(256.0 * colorscales[i])) for i in range(n)]
        except AssertionError:
            # assume we have a list of strings now.
            logger.debug("could not cast 'state_colors' to numeric values.")

        # set arrow labels
        if isinstance(arrow_labels, _np.ndarray):
            L = arrow_labels
            if isinstance(arrow_labels[0,0], str):
                arrow_label_format = '%s'
        elif isinstance(arrow_labels, str) and arrow_labels.lower() == 'weights':
            L = self.A[:, :]
        elif arrow_labels is None:
            L = _np.empty(_np.shape(self.A), dtype=object)
            L[:, :] = ''
            arrow_label_format = '%s'
        else:
            raise ValueError('invalid arrow labels')

        # draw circles
        circles = []
        for i in range(n):
            # choose color
            c = _plt.Circle(
                self.pos[i], radius=_sqrt(
                    0.5 * state_sizes[i]) / 2.0,
                color=state_colors[i], zorder=2)
            circles.append(c)
            self.ax.add_artist(c)
            # add annotation
            if state_labels is not None:
                self.ax.text(self.pos[i][0], self.pos[i][1], state_labels[i], zorder=3, **textkwargs)

        assert len(circles) == n, "%i != %i" % (len(circles), n)

        # draw arrows
        for i in range(n):
            for j in range(i + 1, n):
                if (abs(self.A[i, j]) > 0):
                    self._draw_arrow(
                        self.pos[i, 0], self.pos[i, 1], self.pos[j, 0], self.pos[j, 1], Dx, Dy,
                        label=arrow_label_format%L[i, j], width=arrow_scale * self.A[i, j],
                        arrow_curvature=arrow_curvature, patchA=circles[i], patchB=circles[j],
                        shrinkA=3, shrinkB=0, arrow_label_size=arrow_label_size)
                if (abs(self.A[j, i]) > 0):
                    self._draw_arrow(
                        self.pos[j, 0], self.pos[j, 1], self.pos[i, 0], self.pos[i, 1], Dx, Dy,
                        label=arrow_label_format%L[j, i], width=arrow_scale * self.A[j, i],
                        arrow_curvature=arrow_curvature, patchA=circles[j], patchB=circles[i],
                        shrinkA=3, shrinkB=0, arrow_label_size=arrow_label_size)

        # plot
        self.ax.set_xlim(xmin, xmax)
        self.ax.set_ylim(ymin, ymax)
        return fig
197492
def plot(self, numPoints=100):
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    # generate sphere
    phi, theta = np.meshgrid(
      np.linspace(0, pi, numPoints),
      np.linspace(0, 2 * pi, numPoints)
    )
    x = self.radius * np.sin(phi) * np.cos(theta)
    y = self.radius * np.sin(phi) * np.sin(theta)
    z = self.radius * np.cos(phi)

    # plot
    ax.plot_surface(x, y, z, alpha=0.2, rstride=20, cstride=10)
    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.set_zlabel("Z")

    plt.title("{}".format(self))
    return fig, ax