How to Draw an 2d Array - python

How could I graph this array u,
import math
import numpy as np
import matplotlib.pyplot as plt
pi=np.arccos(-1)
#Parameters En la ecuación del calor 1D
L = 1.;
T =1.;
#Parámetros del método
maxk = 2500; # Divisiones temporales
dt = T/maxk;
n = 50; # Divisiones espaciales
dx = L/n;
cond = 1/4; # Conductividad
b = 2.*cond*dt/(dx*dx); # Alpha
u=[[None]*maxk]*n
x=[None]*n
time=[None]*maxk
# Suponga temperatura distribuida de forma senoidal en la varilla para t=0
for i in range(0,n):
x[i] =i*dx;
u[i][0] =np.sin( pi*x[i] );
# Suponga una frontera a temperatura cero
for k in range(0,maxk):
u[0][k] = 0.;
u[n-1][k] = 0.;
time[k] = k*dt;
#Metodo explicito de solucion
for k in range(0,maxk-1):
for i in range(1, n-2):
u[i][k+1] =u[i][k] + 0.5*b*u[i-1][k]+u[i+1][k]-2.*u[i][k];
fig = plt.figure(figsize=(16, 13.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(u)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
I would expect a result like this
but I get something like this

Related

How to animate matplotlib.imshow()?

I am a physics student trying to simulate the 2D Ising model using the Metropolis algorithm in Python. I wanted to see the time evolution of imshow() and used the following code below. But the program outputs a blank graph. What do I do? Thank you for your help!!
n = 50
ims =[]
def lattice(p):
init_random = np.random.random((n,n))
d = np.zeros((n,n))
d[init_random>=p] = 1
d[init_random<p] = -1
return d
def energy(lattice):
kern = generate_binary_structure(2, 1)
kern[1][1] = False
e = -lattice * convolve(lattice, kern, mode='constant', cval=0)
return e.sum()
def metropolis(s, b, t, e):
s = s.copy()
for t in range(0,t-1):
x = np.random.randint(0,n)
y = np.random.randint(0,n)
si = s[x,y]
sf = -1*si
ei = 0
ef = 0
if x > 0:
ei += -si*s[x-1,y]
ef += -sf*s[x-1,y]
if x < n-1:
ei += -si*s[x+1,y]
ef += -sf*s[x+1,y]
if y > 0:
ei += -si*s[x,y-1]
ef += -sf*s[x,y-1]
if y < n-1:
ei += -si*s[x,y+1]
ef += -sf*s[x,y+1]
de = ef - ei
if (de>0)*(np.random.random() < np.exp(-b*de)):
s[x,y] = sf
elif (de<=0):
s[x,y] = sf
im = plt.imshow(s, animated = True)
ims.append([im])
return ims
u = lattice(0.25)
e = energy(u)
fig = plt.figure(figsize=(6,6))
ims = metropolis(u, 0.7, 100, e)
ani = animation.ArtistAnimation(fig, ims, interval = 50, blit = True, repeat_delay = 100)
plt.show()
I only needed to add the imports and change the def energy section (specifically the e= line). It works nicely in my system.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import ndimage, convolve
n = 50
ims =[]
def lattice(p):
init_random = np.random.random((n,n))
d = np.zeros((n,n))
d[init_random>=p] = 1
d[init_random<p] = -1
return d
def energy(lattice):
kern = ndimage.generate_binary_structure(2, 1)
kern[1][1] = False
e = -lattice * ndimage.convolve(lattice, kern, mode='constant', cval=1)
return e.sum()
def metropolis(s, b, t, e):
s = s.copy()
for t in range(0,t-1):
x = np.random.randint(0,n)
y = np.random.randint(0,n)
si = s[x,y]
sf = -1*si
ei = 0
ef = 0
if x > 0:
ei += -si*s[x-1,y]
ef += -sf*s[x-1,y]
if x < n-1:
ei += -si*s[x+1,y]
ef += -sf*s[x+1,y]
if y > 0:
ei += -si*s[x,y-1]
ef += -sf*s[x,y-1]
if y < n-1:
ei += -si*s[x,y+1]
ef += -sf*s[x,y+1]
de = ef - ei
if (de>0)*(np.random.random() < np.exp(-b*de)):
s[x,y] = sf
elif (de<=0):
s[x,y] = sf
im = plt.imshow(s, animated = True)
ims.append([im])
return ims
u = lattice(0.25)
e = energy(u)
fig = plt.figure(figsize=(6,6))
ims = metropolis(u, 0.7, 100, e)
ani = animation.ArtistAnimation(fig, ims, interval = 50, blit = True, repeat_delay = 100)
plt.show()

MatPlotLib Graphs not showing

I am a begginer programmer and I'm trying to plot some graphs in python with math libraries and But I have some trouble.
I have to find some coordinates on the graph, sequentially, but the line simply doesnt appear on the screen, just the grid.
import math
import cmath
import numpy as np
from sympy import symbols, Eq, solve
import matplotlib.pyplot as plt
pi = 3.14159265
eps_r = 1.14
f = 27e6
Zo = 50
ZL = 50+75j
#começa a função
c = 299792458
vp = c / math.sqrt(eps_r)
Lambda = vp / f # comprimento de onda
Beta = 2 * pi / Lambda
d = np.arange(0, 1e-4, Lambda/4) # Distância da Impedância na linhaà carga
Z_d = (Zo * ((ZL + 1j * Zo * math.tan(Beta * d)) / (Zo + 1j * ZL * math.tan(Beta * d)))) / Zo # impendandia na linha a distancia d
Y_d = 1 / Z_d # Y_d = Admitância
Re_Y = np.real(Y_d)
Im_Y = np.imag(Y_d)
fig, ax = plt.subplots()
ax.plot(d, Re_Y)
ax.set(xlabel='d (m)', ylabel='Y(d) (1/Ohm)',
title='Real da Admitância vs distância à carga (1/Ohm)')
ax.grid()
plt.show()
plt.plot(d, Im_Y)
plt.grid(True, which="both")
plt.title('Imaginário da Admitância vs distância à carga (1/Ohm)')
plt.xlabel('d (m)')
plt.ylabel('jY(d) (1/Ohm)')
plt.show()
Zin_Y = 1 / (-1j * Im_Y) * Zo
lstubv = (cmath.atan (Zin_Y / (1j*Zo)) ) / Beta
lstubv = abs(lstubv)
plt.plot(Im_Y, lstubv)
plt.grid(True, which="both")
plt.title('módulo do Comprimento do STUB vs Y (1/Ohm)')
plt.xlabel('Yin (1/Ohm')
plt.ylabel('l (m))')
plt.show()
K = np.zeros(np.size(d))
for ct in range(1, 1, np.size(d, 2)):
if .9999 <= Re_Y(ct) and Re_Y(ct) <= 1.0001:
K = ct
k = np.mean(K)
if k == 0:
k = np.find(abs(Re_Y - 1) < 1e-6)
k = np.mean(k)
x = (math.ceil(np.mean(k)))
dstub = x * 1e-4
print('Distância do stub à carga (m)'), print(dstub)
Imstub = Im_Y(x)
Zin = 1 / (-1j * Imstub) * Zo
lstub = symbols('l')
lstub = abs((solve(Zin - 1j * Zo * math.tan(Beta * lstub), lstub)))
xLam_Stub = (lstub / Lambda)
print('Comprimento do stub em curto (m)'), print(lstub)
print('Distância do stub à carga (m)'), print(dstub)
this is my code. When I run it, the graphs appear, but...
Graph1 Graph2 Graph3
Also, I received this error after closing the graphs windows
error message

Why does execution time of the same algorithm changes so much when it is coded inside a module in numpy

In my learning process, I am writing a value function iteration problem in two different ways.
All code inside a python file
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
import rutinas as rt
# Tenemos que definir lo parametros
alpha = .33
delta = .07
sigma = 1.5
gamma = 0 # Vamos a considerar que los hogares no valoran el ocio
beta = .97
tfp = 1.0
# Definicion de estados estaionarios
sss = alpha*delta/(1.0/beta-1.0+delta)
lss = (1.0-alpha)/(1.0-alpha+gamma*(1-sss))
kss = (alpha*tfp/(1.0/beta-1.0+delta))**(alpha/(1.0-alpha))
yss = tfp*kss**alpha*lss**(1.0-alpha)
css = (1.0-sss)*yss
# Definimos un grid para la variable de estado de la economía
nk = 500
kmin = 1.0e-5
kmax = 4*kss
kgrid = np.linspace(kmin, kmax, nk)
# Definimos una matriz de consumos. Esto puede hacerse de dos formas:
# 1. Preasignando y llenado espacios
matrizC = np.empty((nk, nk))
matrizU = np.empty((nk, nk))
for i1 in range(0,nk):
for i2 in range(0,nk):
matrizC[i1, i2] = tfp*kgrid[i1]**alpha\
+ (1.0-delta)*kgrid[i1]\
- kgrid[i2]
# Un indicador de posiciones de consumo positivas
indC = matrizC <= 0
matrizU = matrizC**(1.0-sigma)/(1.0-sigma)
matrizU[indC] = -1.e+6
# A partir de aquí podemos inicializar el algoritmo de programacion dinamica
valorInit = np.zeros(nk)
valorObj = np.zeros((nk, nk))
# Criterio de convergencia del algoritmo
tol = 1e-6
# Inicializamos el bucle while y un error arbitrario inicial
cont = 0
error = 10
while error > tol:
for i2 in range(0, nk):
valorObj[:, i2] = matrizU[:, i2] + beta*valorInit[i2]
pos = valorObj.argmax(axis = 1)
valor = valorObj.max(axis = 1)
error = np.max(np.abs(valor-valorInit))
valorInit = valor
cont += 1
print(error)
Inside a module with other routines
The algorithm inside the routine is a copy-paste of the previous file
def mnc_bellman(param):
import numpy as np
# Declaramos los argumentos del problema de programacion dinamica
# tol, kmin, kmax, tam, valorInit = args
alpha, delta, sigma, gamma, beta, tfp = param
kss = (alpha * tfp / (1.0 / beta - 1.0 + delta))**(alpha / (1.0 - alpha))
tol = 1.0e-6
kmin = 1.0e-4
kmax = 4*kss
tam = 500
valorInit = np.zeros((tam))
# Inicializamos objetos que vamos a necesitar
matrizC = np.empty((tam, tam))
valorObj = np.zeros((tam, tam))
kgrid = np.linspace(kmin, kmax, tam)
for i1 in range(0, tam):
for i2 in range(0, tam):
matrizC[i1, i2] = tfp * kgrid[i1] ** alpha \
+ (1.0 - delta) * kgrid[i1] \
- kgrid[i2]
# Un indicador de posiciones de consumo positivas
indC = matrizC <= 0
matrizU = matrizC ** (1.0 - sigma) / (1.0 - sigma)
matrizU[indC] = -1.e+6
# A partir de aqui podemos inicializar el algoritmo ITERACION de la
# funcion de VALOR
# Esta variable va a guardar cuantas veces iteramos hasta cumplir con los
# criterios de convergencia
cont = 0
# Tambien tenemos que establecer un error inicial que no se satisfaga
# trivialmente en el primer paso del bucle
error = 10
while error > tol:
for i2 in range(0, tam):
valorObj[:, i2] = matrizU[:, i2] + beta * valorInit[i2]
pos = valorObj.argmax(axis=1)
valor = valorObj.max(axis=1)
error = np.max(np.abs(valor - valorInit))
valorInit = valor
cont += 1
print(error)
# Ahora reconstruimos las reglas de decision
reglaK = kgrid[pos]
reglaC = tfp * kgrid ** alpha + (1.0 - delta) * kgrid - reglaK
return valor, reglaK, reglaC
That I later call from a main program
import numpy as np
import numpy.matlib
#import matplotlib.pyplot as plt
#from scipy.optimize import fsolve
import rutinas as rt
# Definicion de parametros del modelo (posteriormente intentare meterlos en un
# diccionario)
alpha = .36
delta = .08
sigma = 1.5
gamma = 0.5
beta = .97
tfp = 1.0
# Definicion de estado estacionario correspondiente a los parametros del
# modelo
sss = alpha * delta / (1.0 / beta - 1.0 + delta)
lss = (1.0 - alpha) / (1.0 - alpha + gamma * (1.0 - sss))
kss = (alpha * tfp / (1.0 / beta - 1.0 + delta))**(alpha / (1.0 - alpha))
yss = tfp * kss**alpha * lss**(1.0 - alpha)
css = (1.0 - sss) * yss
# Parametros relacionados con el algoritmo de iteracion de la funcion de valor
tol = 1.0e-6
kmin = 1.0e-4
kmax = 3.0*kss
tam = 500
valorInit = np.zeros((tam))
param = [alpha, delta, sigma, gamma, beta, tfp]
valor, reglaK, reglaC = rt.mnc_bellman(param)
Both codes run and spit the same output. However, the second option is orders of magnitude slower.
I hope somebody could point me into how to solve this discrepancy. I was thinking about using Jit but I want to understand the problem first.
Thank you

Nested for loop and 3D Plot within Class Object

i am sure this is an easy problem to deal with, but i cant figure it out. I created a Borehole Class and want to compute my pore pressure around each Borehole/Well. Along a single axis, my code looks like this:
from scipy.special import *
import matplotlib.pyplot as plt
import numpy as np
from math import *
## Globale Variablen ##
rhof = 1000 # Dichte Flüssigkeit [kg/m³]
lameu = 11.2*10**9 # Lamé-Parameter, undrained [GPa]
lame = 8.4*10**9 # Lamé-Parameter, drained [GPa]
pi # durch Pythonmodul "math" gegeben
alpha = 0.65 # Biot-Willis-Koeffizient
G = 8.4*10**9 # Schermodul [GPa]
k = 1.0e-15 # Permeabilität [m²] bzw. [Darcy]
eta = 0.001 # Viskosität des Fluids [Pa*s]
## Berechnung der Parameter ##
kappa = k/eta
c = ((kappa*(lameu-lame)*(lame+2*G))/((alpha**2)*(lameu+2*G)))
## Wertebereich ##
xmin = 0
xmax = 100
xsteps = 1.0
x = np.arange(xmin, xmax, xsteps)
## Class ##
class Bohrloch(object):
loch_zaehler = 0
def __init__(self, xlage, tstart, q): # Funktion, um BL zu erzeugen
self.xlage = xlage
#self.ylage = ylage # Lage der Bohrung
self.tstart = tstart # Start der Injektion/Produktion
self.q = q # Fluidmenge
## Druck ##
def getPressure(self, t): # gibt nach Zeit t die zugehörigen Druckwerte aus
if (t-self.tstart<0): # Fehlermeldung, falls Startpunkt nach t liegt
return ()
print "Startpunkt liegt außerhalb des Förderzeitraumes!"
else:
self.r = np.sqrt((x-self.xlage)**2)
self.P = (self.q/(rhof*4*pi*kappa))*(expn(1,self.r**2/(4*c*(t-self.tstart))))
#self.P[self.xlage] = 0 # gibt Bohrlochlage wieder
self.z = self.P/1e6
return self.z # Druckwerte in [MPa]
def pressureTable (self, t, xschritt): # erstellt Wertetabelle
self.getPressure(t)
for i in range (xmin, xmax, xschritt):
print i, " ", self.z[i]
t = 1000*24*3600
b1 = Bohrloch(50,0*24*3600,6.0/1000)
b1.pressureTable(t,1)
With this method i get my desired pressure table. Now i want to have a pressure table for x and y values, including an 3D Plot. This is my code so far:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from scipy.special import *
import matplotlib.pyplot as plt
import numpy as np
from math import *
## Globale Variablen ##
rhof = 1000 # Dichte Flüssigkeit [kg/m³]
lameu = 11.2*10**9 # Lamé-Parameter, undrained [GPa]
lame = 8.4*10**9 # Lamé-Parameter, drained [GPa]
pi # durch Pythonmodul "math" gegeben
alpha = 0.65 # Biot-Willis-Koeffizient
G = 8.4*10**9 # Schermodul [GPa]
k = 1.0e-15 # Permeabilität [m²] bzw. [Darcy]
eta = 0.001 # Viskosität des Fluids [Pa*s]
## Berechnung der Parameter ##
kappa = k/eta
c = ((kappa*(lameu-lame)*(lame+2*G))/((alpha**2)*(lameu+2*G)))
## Wertebereich ##
xmin = 0
xmax = 100
xsteps = 1.0
x = np.arange(xmin,xmax,xsteps)
ymin = 0
ymax = 100
ysteps = 1.0
y = np.arange(ymin,ymax,ysteps)
## Klassendefinition ##
class Bohrloch(object):
loch_zaehler = 0
def __init__(self, xlage, ylage, tstart, q): # Funktion, um BL zu erzeugen
self.xlage = xlage # x-Lage der Bohrung
self.ylage = ylage # y-Lage der Bohrung
self.tstart = tstart # Start der Injektion/Produktion
self.q = q # Fluidmenge
## Druck ##
def getPressure(self, t):
if (t-self.tstart<0):
return ()
print "Startpunkt liegt außerhalb des Förderzeitraumes!"
else:
self.r = np.sqrt((x-self.xlage)**2+(y-self.ylage)**2)
self.P = (self.q/(rhof*4*pi*kappa))*(expn(1,self.r**2/(4*c*(t-self.tstart))))
self.P[self.xlage] = np.nan
self.P[self.ylage] = np.nan
self.z = self.P/1e6
return self.z # Druckwerte in [MPa]
def pressureTable (self, t, xschritt, yschritt):
self.getPressure(t)
for k in range (xmin, xmax, xschritt):
for l in range (ymin, ymax, yschritt):
# my mistake should be here?
print k, " ", l, " ", self.z[k][l]
def pressurePlot3D (self, t):
self.getPressure(t)
Z = self.z
X, Y = np.meshgrid(x,y)
Z[Z == np.inf] = np.nan
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0,
antialiased=False, vmin=np.nanmin(Z), vmax=np.nanmax(Z))
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_xlim(xmin,xmax) # x-Achsenskala vorgeben
ax.set_ylim(ymin,ymax) # y-Achsenskala vorgeben
ax.set_title('Druckverteilung')
ax.set_xlabel('x-Richtung [m]')
ax.set_ylabel('y-Richtung Well [m]')
ax.set_zlabel('Druck in [MPa]')
plt.show()
t = 1000*24*3600
b1 = Bohrloch(50,50,0*24*3600,6.0/1000)
b1.pressureTable(t,1)
b1.pressurePlot3D(t)
Unfortunately, my table doesnt work and the desired 3D Plot looks strange. I am still a total beginner in Python and need some advices.
Can anyone help?
The problem is that self.z is not a two-dimensional array/list. Therefore, trying to access self.z[k][l] results in IndexError: invalid index to scalar variable.
I do not quite understand how you want to implement the second dimension. You introduce the y-position, but then, you just calculate a 1D radius array by using both the x- and y-location in
self.r = np.sqrt((x-self.xlage)**2+(y-self.ylage)**2)
The next question is, what do you intend with:
self.P[self.xlage] = np.nan
self.P[self.ylage] = np.nan
If you change xsteps and ysteps to 10, and call:
b1 = Bohrloch(2,3,0*24*3600,6.0/1000)
print b1.getPressure(t)
Your output will be:
[ 5.44152501 4.40905986 nan nan 2.87481753 2.64950827
2.46756653 2.31503845 2.18379093 2.06866598]
Why would you want to replace the 3rd and 4th elements with nan?
These issues are also at the basis of your plotting routine. Because you now have np.nan values in your array, these won't show in the plot. Because self.z is not two-dimensional, you are probably not getting the surface you may be expecting:
Here's a simple way of coming up with a 2D implementation. I am not familiar enough with what you are trying to do, but it gets the idea across:
def getPressure(self, t):
if (t-self.tstart<0):
return ()
print "Startpunkt liegt außerhalb des Förderzeitraumes!"
else:
# you need to initialize r, P and z as list of lists
# make this dependent on your x coordinates
# the second dimension will grow dynamically
self.r = [[] for ri in range(len(x))]
self.P = [[] for ri in range(len(x))]
self.z = [[] for ri in range(len(x))]
# iterate through both x and y independently
for ii in range(len(x)):
for jj in range(len(y)):
# append to the list that corresponds to the current x -value
# also, use x[ii] and y[jj] to call one x-, y-value at a time
self.r[ii].append(np.sqrt((x[ii]-self.xlage)**2+(y[jj]-self.ylage)**2))
# calling r[ii][-1] ensures you are using the value that was last added to the list:
self.P[ii].append((self.q/(rhof*4*pi*kappa))*(expn(1,self.r[ii][-1]**2/(4*c*(t-self.tstart)))))
self.z[ii].append(self.P[ii][-1]/1e6)
# now, you can use xlage and ylage to blank one value
# do this for both P and z, because z is now calculated inside the loop
self.P[self.xlage][self.ylage] = np.nan
self.z[self.xlage][self.ylage] = np.nan
return self.z
From your plotting routine, remove this line: Z[Z == np.inf] = np.nan, use your original command:
b1 = Bohrloch(50,50,0*24*3600,6.0/1000)
b1.pressurePlot3D(t)
and you will now get this plot:

Dynamical plot with Chaco

I need to add some points to an existent plot I do in chaco. I have tried with plot.request_redraw() but it didn't work. What else can I do?
This is the piece of code:
class PlotApp(HasTraits):
plotdata = Instance(ArrayPlotData)
returns_plot = Instance(Plot)
plot_type = Enum('line', 'scatter')
corr_renderer = Any()
x_min = Float()
x_max = Float()
traits_view = View(
VGroup(
HGroup(spring, Label('Click point to select/unselect'),
spring),
#Item('plot_type'),
Item('returns_plot', editor=ComponentEditor(size=size,
bgcolor=bg_color),
show_label=False),
#Item('num_medicion', width=-225),
orientation = "vertical"),
resizable=True, title=title
)
def _create_returns_plot(self):
plot = Plot(self.plotdata)
plot.legend.visible = True
plot.x_axis = None
x_axis = PlotAxis(plot, orientation="bottom")
plot.overlays.append(x_axis)
renderer = plot.plot(("index", "value"), type="scatter",name = "Mediciones")[0]
#Agrego todas las tools necesarias
renderer.tools.append(ScatterInspector(renderer, selection_mode="toggle", persistent_hover=False))
renderer.overlays.append(
ScatterInspectorOverlay(renderer,
hover_color = "transparent",
hover_marker_size = 10,
hover_outline_color = "purple",
hover_line_width = 2,
selection_marker_size = 8,
selection_color = "red")
)
renderer.tools.append(RangeSelection(renderer, left_button_selects = False, disable_left_mouse = True, \
rigth_button_selects = True, \
auto_handle_event = False, metadata_name = "annotations"))
renderer.overlays.append(RangeSelectionOverlay(component=renderer, metadata_name = "annotations"))
renderer.tools.append(PanTool(renderer))
renderer.overlays.append(ZoomTool(renderer, drag_button="right"))
self.index_datasource = renderer.index
self.index_datasource.on_trait_change(self._selections_changed, "metadata_changed")
self.returns_plot = plot
def _create_data(self):
#genero los datos, más adelante los voy a leer con pandas
npts = 40
x_max = 10
x = np.random.random(npts)
x = x * x_max
error = np.random.random(npts)
y = 2 + 3*x + 5*error
#Esta parte es para ordenar los elementos
x_ordenado = np.array([])
y_ordenado = np.array([])
orden = range(x.size)
nuevo_orden = np.array([])
for i in range(x.size):
arg_min = x.argmin()
x_ordenado = np.append(x_ordenado, x[arg_min])
y_ordenado = np.append(y_ordenado, y[arg_min])
nuevo_orden = np.append(nuevo_orden, orden[arg_min])
x = np.delete(x, arg_min)
y = np.delete(y, arg_min)
orden = np.delete(orden, arg_min)
self.x_ordenado = x_ordenado
self.y_ordenado = y_ordenado
#Genero el retorno para el plot
plotdata = ArrayPlotData()
plotdata.set_data("index", x_ordenado)
plotdata.set_data("value", y_ordenado)
self.plotdata = plotdata
def _selections_changed(self):
#Obtengo los puntos marcados manualmente
self.posicion_puntos_selec = self.index_datasource.metadata.get('selections', ())
#obtengo los puntos que marque con el rectangulo
seleccionado_range = self.index_datasource.metadata.get('annotations', ())
#Cuando desmarcon con el rectangu, el tipo de annotations es NoneType,
#con este if lo cambio a tuple
type_range = type(self.index_datasource.metadata['annotations'])
if type_range != tuple:
self.index_datasource.metadata['annotations'] = []
else:
self.x_min, self.x_max = seleccionado_range
#on_trait_change("posicion_puntos_selec, x_min, x_max")
def _perform_calculations(self):
plot = self.returns_plot
x_nuevo = np.append(self.x_calcular, [11, 12])
y_nuevo = np.append(self.y_calcular, [11, 12])
self.corr_renderer = plot.plot((x_nuevo, y_nuevo),
type="scatter", color="blue")[0]
plot.request_redraw()
To update the data of an existing plot, the best and simplest is to update the existing ArrayPlotData of the existing Plot instance being displayed. There are listeners inside Chaco that will take care of the redraw. Below is an example inspired from your code:
from traits.api import HasTraits, Enum, Instance, Button
from traitsui.api import View, Item, VGroup
from enable.api import ComponentEditor
from chaco.api import Plot, ArrayPlotData, PlotAxis
from numpy import arange
class PlotApp(HasTraits):
plotdata = Instance(ArrayPlotData)
returns_plot = Instance(Plot)
plot_type = Enum('line', 'scatter')
add_points = Button
traits_view = View(
VGroup(Item("add_points"),
Item('returns_plot', editor=ComponentEditor(),
show_label=False),
orientation = "vertical"),
resizable=True, title="Test"
)
def _returns_plot_default(self):
self.plotdata = ArrayPlotData(index=arange(100), value=arange(100))
plot = Plot(self.plotdata)
plot.legend.visible = True
plot.x_axis = None
x_axis = PlotAxis(plot, orientation="bottom")
plot.overlays.append(x_axis)
plot.plot(("index", "value"), type="scatter", name = "Mediciones")
return plot
def _add_points_fired(self):
current_length = len(self.plotdata["index"])
self.plotdata.set_data("index", arange(current_length+1))
self.plotdata.set_data("value", arange(current_length+1))
if __name__ == "__main__":
app = PlotApp()
app.configure_traits()
HTH,
Jonathan

Categories