'''Draw a z = f(x,y) surface specified as a string or as a reference to an external function. Red points indicate where the function does not exist!''' from vedo import * from vedo.pyplot import plot doc = Text2D(__doc__, pos='bottom-left', c='darkgreen', font='Quikhand') ############################################################### REAL # an existing function z(x,y) can be passed: def my_z(x, y): return sin(2 * x * y) * cos(3 * y) / 2 f1 = plot(my_z, c='summer') # use a colormap # f1 = plot(my_z, c='lightblue', bc='tomato') # red dots are shown where the function does not exist (y>x): f2 = plot("sin(3*x)*log(x-y)/3") # specify x and y ranges and z vertical limits: f3 = plot("log(x**2+y**2-1)", xlim=[-2, 2], ylim=[-1, 8], zlim=[-1, None]) show([ (f1, 'y = sin(2*x*y) * cos(3*y) /2', doc), (f2, 'y = sin(3*x)*log(x-y)/3'), (f3, 'y = log(x**2+y**2-1)'), ], N=3, sharecam=False)
from vedo.pyplot import plot import numpy as np x = np.linspace(0, 10, num=21) y = 3 * np.sin(x) errs = np.ones_like(x) / 2 ################# first plot plt = plot( x, y, "*r-", # markers: *,o,p,h,D,d,v,^,s,x,a xtitle="x variable (mm)", ytitle="y(x)", aspect=16 / 9, # aspect ratio x/y of plot # xlim=(-1, 14), # specify x range # ylim=(-4, 5), # specify y range ) ################# plot on top of plt plt.plot( x + 3, y, "sb--", xerrors=errs, # set error bars on x yerrors=errs, # set error bars on y spline=True, # continous line through points lw=1.5, ) ################## plot again on top of plt
n = 1000 x = np.random.randn(n) y = np.random.randn(n) # define what size must have each marker: marker_sizes = np.sin(2 * x) / 8 # define a (r,g,b) list of colors for each marker: marker_cols = np.c_[np.cos(2 * x), np.zeros(n), np.zeros(n)] txt0 = Text2D("A scatter plot of a\n2D gaussian distribution") plt0 = plot( x, y, ma=0.3, lw=0, # ma = marker alpha marker="*", # marker style xtitle="variable A", ytitle="variable B", ) txt1 = Text2D("marker size proportional to sin(2x) ") plt1 = plot( x, y, ma=0.3, lw=0, marker="*", # marker style ms=marker_sizes, # VARIABLE marker sizes mc='red', # same fixed color for markers )
circle = Circle(cpt, r=500, res=36).wireframe() pts = circle.points() # 3d coords of the points of the circle centers = np.zeros_like(pts) + cpt # create the same amount of center coords lines = Lines(centers, pts, res=50) # create Lines with 50 pts of resolution each msh = pic.tomesh() # transform the picture into a quad mesh lines.interpolateDataFrom(msh, N=3) # interpolate all msh data onto the lines rgb = lines.pointdata['RGBA'] # extract the rgb intensities intensities = np.sum(rgb, axis=1) # sum the rgb values into one single intensty intensities_ray = np.split(intensities, 36) # split array so we can index any radius mean_intensity = np.mean(intensities_ray, axis=0) # compute the average intensity # add some optional plotting here: plt = plot(mean_intensity, lc='black', lw=5, spline=True, xtitle='radial distance', ytitle='intensity', aspect=16 / 9) for i in range(0, 36, 3): plt += plot(intensities_ray[i], lc=i, lw=1) plt.scale(21).shift(10, -750) # scale up and move plot below the image show(msh, circle, lines, plt, __doc__, size=(625, 1000), zoom='tight')
"""A simple scatter plot""" from vedo import show from vedo.pyplot import plot import numpy as np x = np.random.randn(100) + 10 y = np.random.randn(100) * 20 plt = plot( x, y, lw=0, xtitle="variable x", ytitle="variable y", aspect=4 / 3, # aspect ratio marker="*", # marker style mc="dr", # marker color axes=True, ) # show Assembly object and lock interaction to 2d: # (can zoom in a region w/ mouse, press r to reset) show(plt, __doc__, viewup='2d')
bg='black', resetcam=True, sharecam=False, offscreen=True) vplt1.show(coloredMesh, verPoints, title='Patient{}, Back View'.format(patient), camera=cam1) video1.addFrame() vplt2 = Plotter(offscreen=True) errplt = plot(x, y, 'o', title='Patient{}, \DeltaE(m)'.format(patient), xtitle='m', ytitle=r'\DeltaE', xlim=[0, m + 1], ylim=[0, ymax], axes={'xyPlaneColor': 'white'}) vplt2.show(errplt) video2.addFrame() if m != stop - 1: vplt0.close() vplt1.close() vplt2.close() video0.close() video1.close() video2.close()
n = 25 # nr of data points to generate deg = 3 # degree of the fitting polynomial # Generate some noisy data points x = np.linspace(0, 12, n) y = (x-6)**3 /50 + 6 # the "truth" is a cubic fuction! xerrs = np.linspace(0.4, 1.0, n) # make last points less precise yerrs = np.linspace(1.0, 0.4, n) # make first points less precise # xerrs = yerrs = None #assume errors are all the same (but unknown) noise = np.random.randn(n) # Plot the noisy points with their error bars plt = plot(x, y+noise, '.k', title=__doc__+str(deg), xerrors=xerrs, yerrors=yerrs, aspect=8/9, xlim=(-3,15), ylim=(-3,15), ) plt += DashedLine(x, y) # Fit points and evaluate, with a boostrap and Monte-Carlo technique, # the correct errors and error bands. Return a Line object: pfit = fit([x, y+noise], deg=deg, # degree of the polynomial niter=500, # nr. of MC iterations to compute error bands nstd=2, # nr. of std deviations to display xerrors=xerrs, # optional array of errors on x yerrors=yerrs, # optional array of errors on y vrange=(-3,15), # specify the domain of fit )
"""Picture in picture plotting""" from vedo import show from vedo.pyplot import plot import numpy as np x = np.arange(0, 4, 0.1) y1 = 3 * np.exp(-x) y2 = 3 * np.exp(-x) * np.cos(2 * x)**2 axes_opts = dict(numberOfDivisions=3, xyPlaneColor='lavender', xyAlpha=1) # Build first plot and its axes: plt1 = plot( x, y1, title=__doc__, xtitle='time in seconds', ytitle='some function [a.u.]', ) # Build second plot and its axes: plt2 = plot( x, y2, title='my second plot', xtitle='time in seconds', ytitle='some other function', lc='red', pad=0, # no margins axes=axes_opts, )
"""Probe a Volume with a line and plot the intensity values""" from vedo import * from vedo.pyplot import plot vol = load(datadir+'vase.vti') vol.addScalarBar3D(title='vase', c='k', italic=1) p1, p2 = (10,10,10), (90,90,90) pl = probeLine(vol, p1, p2, res=50).lineWidth(4) xvals = pl.points()[:,0] yvals = pl.getPointArray() plt = plot(xvals, yvals, spline=True, lc="r", # line color marker="*", # marker style mc="dr", # marker color ms=0.6, # marker size ) show([(vol, pl, __doc__), plt], N=2, sharecam=False)
"""Use of plot() function analogous to matplotlib""" import numpy as np, vtk from vedo import * from vedo.pyplot import plot x = np.linspace(0, 5, 10) plt1 = plot(x, x * x, 'sg-', title='Plot1: y=x*x') plt2 = plot(x, cos(x), 'pr--', title='Plot2: y=cos(x)') plt3 = plot(x, sqrt(x), 'Db-', title='Plot3: y=sqrt(x)') plt4 = plot(x, sin(x), '*t--', title='Plot4: y=sin(x)') # window shape can be expressed as "n/m" or "n|m" show(plt1, plt2, plt3, plt4, shape="3|1", sharecam=False, size=(1300, 900)) printc('plt1 is vtkAssembly?', isinstance(plt1, vtk.vtkAssembly))
from vedo.pyplot import plot, settings import numpy as np settings.defaultFont = 'Kanopus' x = np.linspace(0, 10, num=21) y = 3 * np.sin(x) errs = np.ones_like(x) / 2 ################# first plot plt = plot( x, y, "*r-", # markers: *,o,p,h,D,d,v,^,s,x,a title=__doc__, xtitle="t variable (\mus)", ytitle="y(x) = \pmK_i \dot\sqrtsin^2 t", aspect=16 / 9, # aspect ratio x/y of plot # xlim=(-1, 14), # specify x range # ylim=(-4, 5), # specify y range ) ################# plot on top of plt plt.plot( x + 3, y, "sb--", xerrors=errs, # set error bars on x yerrors=errs, # set error bars on y spline=True, # continous line through points lw=3,
"""Surface plotting in spherical coordinates spherical harmonic function is: Y(l=2, m=0) = 3*cos(theta)**2 - 1 (red points are made NaN on purpose) """ from vedo import * from vedo.pyplot import plot import numpy as np def rhofunc(theta, phi): if theta < 0.2: return np.nan # make some points invalid #return cos(theta)**2 # Y(l=1 m=0) return (3 * cos(theta)**2 - 1)**2 # Y(l=2 m=0) #return (5*cos(theta)**3 - 3*cos(theta))**2 # Y(l=3 m=0) # Build the plot, # return an Assembly of 3 meshes, the unit # grid sphere, the surface rho(theta, phi) and # the red Points where rho is a complex number: spl = plot(rhofunc, mode='spheric', cmap='viridis') show(spl, __doc__, axes=12, viewup='z')
"""Superimpose histograms and curves""" import numpy as np from vedo.pyplot import histogram, plot, settings settings.defaultFont = "Bongas" mu, sigma, n, bins = 100.0, 15.0, 600, 50 samples = np.random.normal(loc=mu, scale=sigma, size=n) x = np.linspace(min(samples), max(samples), num=50) y = 1/(sigma*np.sqrt(2*np.pi)) * np.exp( -(x-mu)**2 /(2*sigma**2)) dy = 1/np.sqrt(n) plt = histogram(samples, title=__doc__, bins=bins, density=True, c='cyan3', aspect=8/7) plt += plot(x, y, "-", lc='orange5') plt += plot(x, y*(1+dy), "--", lc='orange5', lw=2) plt += plot(x, y*(1-dy), "--", lc='orange5', lw=2) plt.show(size=(800,700), zoom=1.2, interactorStyle="Image").close()
'''Draw a z = f(x,y) surface specified as a string or as a reference to an external function. Red points indicate where the function does not exist''' from vedo import * from vedo.pyplot import plot doc = Text2D(__doc__, pos='bottom-right', c='darkgreen', font='Quikhand') ############################################################### REAL # an existing function z(x,y) can be passed: def my_z(x, y): return sin(2 * x * y) * cos(3 * y) / 2 f1 = plot(my_z, c='lb', bc='t') # f1 = plot(my_z, texture=None, bc=None) # f1.unpack(0).addElevationScalars().cmap('terrain') # f1.show() # red dots are shown where the function does not exist (y>x): f2 = plot("sin(3*x)*log(x-y)/3") # specify x and y ranges and z vertical limits: f3 = plot("log(x**2+y**2-1)", xlim=[-2, 2], ylim=[-1, 8], zlim=[-1, None]) show([ (f1, 'y = sin(3*x)*log(x-y)/3', doc), (f2, 'y = log(x**2+y**2-1)'), (f3, 'y = sin(2*x*y) * cos(3*y) /2'), ],
and plot the intensity values""" from vedo import * from vedo.pyplot import plot vol = load(datadir + 'embryo.slc') vol.addScalarBar3D(title='wild-type mouse embryo', c='k') p1, p2 = (50, 50, 50), (200, 200, 200) pl = probeLine(vol, p1, p2, res=100).lineWidth(4) xvals = pl.points()[:, 0] yvals = pl.getPointArray() plt = plot( xvals, yvals, xtitle=" ", ytitle="voxel intensity", aspect=16 / 9, spline=True, lc="r", # line color marker="*", # marker style mc="dr", # marker color ms=0.9, # marker size ) plt.shift(0, 25, 0) show(vol, pl, __doc__, plt, axes=dict(xyGrid=0, yzGrid=0)) # or: #show([(vol, pl, __doc__), plt], N=2, sharecam=False)
"""Fit y=ax+b and compute error bands""" from vedo import Text2D, DashedLine, show from vedo.pyplot import plot, fit import numpy as np # np.random.seed(0) # Generate some noisy data points along a line x = np.linspace(0, 15, 25) a, b = (np.random.rand(2) - 0.5) * 10 # choose a and b y = a * x + b noise = np.random.randn(len(x)) * 5 # create gaussian noise # Plot the points and the "true" line without noise plt = plot(x, y + noise, '*k', title=__doc__) plt += DashedLine(x, y) # Fit points and evaluate, with a boostrap and Monte-Carlo technique, # the correct error coeffs and error bands. Return a Line object: pfit = fit( [x, y + noise], deg=1, # degree of the polynomial niter=500, # nr. of MC iterations to compute error bands nstd=2, # nr. of std deviations to display ) plt += [pfit, pfit.errorBand, *pfit.errorLines] # add these objects to Plot msg = f"Generated a, b : {np.array([a,b])}"\ f"\nFitted a, b : {pfit.coefficients}"\ f"\nerrors on a, b : {pfit.coefficientErrors}"\ f"\nave point spread: \sigma \approx {pfit.dataSigma:.3f} in y units"
from vedo.pyplot import plot # Make up same data x = np.arange(0, 6, 0.1) y = 2+2*np.sin(2*x)/(x+1) ye= y**2 / 10 miny = np.min(y-ye) idx = np.argmax(y) # Plot the two variables, return a Plot(Assembly) object: plt = plot(x,y, yerrors=ye, xtitle='time in \museconds', ytitle='y oscillation [a.u.]', ylim=(0.5, 5), aspect=4/3, # aspect ratio (any float = x_size/y_size) errorBand=True, # join errors on y into an error band lc="k", # line color ec="r", # error band color la=0.6, # error and line alphas pad=0.0, # tight margins, no padding ) # Add a grey transparent rectangle to represent an exclusion region: plt += Rectangle([1,0.5], [2.7,5], alpha=0.2, c='k') # Add some text and latex formula plt += Text3D("Excluded\ntime range!", s=.2, c='k', font="Quikhand").rotateZ(20).pos(1.3, 3.6) plt += Latex(r"y(t)=2+2\cdot\frac{\sin(2t)}{(t+1)}", pos=(4.7, 4.7), s=.8, c='db') # Add a star marker at maximum of function (at z=0.1, so it stays on top): plt += Marker('*', pos=(x[idx], y[idx], 0.1), c='blue')
import numpy as np from vedo import * from vedo.pyplot import histogram, plot cmap = 'nipy_spectral' alpha = np.array([0, 0, 0.05, 0.2, 0.8, 1]) vol = Volume(dataurl + "embryo.slc") vol.cmap(cmap).alpha(alpha).addScalarBar3D(c='w') xvals = np.linspace(*vol.scalarRange(), len(alpha)) p = histogram(vol, logscale=True, c=cmap, bc='white') p += plot(xvals, alpha * p.ybounds()[1], '--ow').z(1) show( [(vol, Axes(vol, c='w'), f"Original Volume\ncolor map: {cmap}"), (p, "Voxel scalar histogram\nand opacity transfer function")], N=2, sharecam=False, bg=(82, 87, 110), ).close()
"A splined polar plot" from vedo import * from vedo.pyplot import plot angles = vector([0, 20, 60, 160, 200, 250, 300, 340]) distances = vector([0.1, 0.2, 0.3, 0.5, 0.6, 0.4, 0.2, 0.1]) dn1 = plot(angles, distances, mode='polar', deg=True, spline=True, fill=True, c='green', bc='k', alpha=0.7, title=__doc__, vmax=0.65) dn2 = plot(angles + 120, distances**2, mode='polar', deg=True, spline=True, fill=True, c='red', alpha=0.7, vmax=0.65) dn2.z(0.01) # set a positive z so it stays in front show(dn1, dn2, zoom=1.2, bg='k9')
import nevergrad as ng # install with: pip install nevergrad def f(x,y): z = (x-1)**2 + (y-1)**2 + 9*sin(y-1)**2 + 1 return z/12 def func(v): return f(v[0],v[1]) def callbk(optimizer, v, value): global minv if value<minv: pts.append([v.value[0], v.value[1], value]) minv = value optimizer = ng.optimizers.OnePlusOne(parametrization=2, budget=100) pts, minv = [], 1e30 optimizer.register_callback("tell", callbk) # define a constraint on first variable of x: #optimizer.parametrization.register_cheap_constraint(lambda v: v[0]>-3) res = optimizer.minimize(func) # best value printc('Minimum at:', res.value) ln = Line(pts, lw=3) fu = plot(f, xlim=[-3,4], ylim=[-3,4], alpha=0.5) show(fu, ln, __doc__)
settings.defaultFont = "Meson" counts = [1946, 8993, 3042, 1190, 1477, 0, 0] percent = [11.68909178, 54.01850072, 18.27246516, 7.14800577, 8.87193657, 0, 0] labels = [ '<100', '100-250', '250-500', '500-750', '750-1000', '1000-2000', '>2000' ] colors = colorMap(range(len(counts)), "hot") plt = plot( [counts, labels, colors], mode="bars", ylim=(0, 10500), aspect=4 / 3, axes=dict( htitle="Clusters in lux range", hTitleItalic=False, xLabelRotation=35, xLabelSize=0.02, tipSize=0, # axes arrow tip size ), ) for i in range(len(percent)): val = precision(percent[i], 3) + '%' txt = Text3D(val, pos=(plt.centers[i], counts[i]), justify="bottom-center", c="blue2") plt += txt.scale(200).shift(0, 150, 0)
xmax=39, value=0, s=0.01, t=2, c="r", rotation=45, title="From eigen component", ) x = np.arange(40) y = plotting_signal p = plot( x, y, ma=0.2, # const. marker alpha lw=0, # no line width aspect=1, # plot aspect ratio ) p.pos(4, 4, z_offest) plt.show(mesh, mesh_90, mesh_180, mesh_270, points, p, "Scalar Spectral TV Decomp ", axes=False)