Why this Mayavi animation stops executing at a random iteration? - mayavi

I read a few questions similar to mine but none of the answers work... I want to make an animation that plots the points of a list one by one. The problem is that from rank 12, it stops. I tested gc.collect(generation=1) but it didn't work... Here is the end of my code :
#mlab.animate(delay=100)
def updateAnimation():
k=0
for k in range(len(X)):
mlab.points3d(X[k], Y[k], Z[k], S[k], color=C[k], scale_factor=10)
yield
updateAnimation()
mlab.show()
X, Y, Z, S and C are lists with a length of 136. I am using python 3.9.12 and mayavi 4.8.0. It's maybe something stupid with set... but I'm new at mayavi.
Thank you very much for any insight.

Related

Trying to use the sum operator in matplotlib gives an error

So I would like to mention first that I am completely new to basically everything that is linked to Jupyter Notebook, matplotlib and numpy stuff. So that's why I most likely will not be able to express my problem clearly. Therefore I am begging for your patience :) (ah yeah and my English sucks too so...)
Anyways, I am trying to create an interactive plot. Therefore, I want to display the function of the first n polynomes of the square wave where the value of n can be choosen by using a slider. This is what I got so far:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (11,4)
plt.rcParams['figure.dpi'] = 150
from ipywidgets import interact,interactive, fixed, interact_manual
import ipywidgets as Widgets
def f(n):
plt.plot( np.arange(0,10), 1/pi * sum( 2/(i* pi) * (1- cos(i*pi) ) * sin(i*np.arange(0,10)) for i in range(1,n) ) )
plt.ylim(-2,2)
interact(f, n= 1)
Now, everything works fine until the line where I set my function, so the line with this
plt.plot(np.arange ...)
It gives me the following error:
ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)
I already figured out that this has to do with the usage of the sum() Operator and using the variable n in it. If i don't put n in the sum, then everything works out nicely and I am getting my graph.
So, the question basically is what I will have to do to make my idea happen.
Thank you for your Responses, I know that my post might be very annoying to some of you because of its style or whatever and I am sorry for that.
Using the sum means you collapse the list of values down to a single value, that's what numpy is telling you - you have 10 x values and only 1 y value (because you just added them all up). I think what you are meaning to do is create a list of sums, so just move one closing parenthesis ()) from after the for i in range(n) to before it:
plt.plot(np.arange(0,10), 1/pi * sum(2/(i* pi) * (1- cos(i*pi)) * sin(i*np.arange(0,10))) for i in range(1,n))
So, for those of you who are interested in the answer (probably there are some): I found a nice and simple solution.
The Problem was the fact, that the line
interact(f, n= 1)
didn't work on its own. Now that I put it like this,
interact(f, n =widgets.IntSlider(min=2, max=100, step=1, value=2))
so by - most importantly - saying that the slider is supposed to be an IntSlider, everything works just fine!
Thank you for your help anyways! Since I am new on this platform, I don't know how solved questions can be closed, but this one here defenitely can be closed.

How does numpy polyfit work?

I've created the "Precipitation Analysis" example Jupyter Notebook in the Bluemix Spark service.
Notebook Link: https://console.ng.bluemix.net/data/notebooks/3ffc43e2-d639-4895-91a7-8f1599369a86/view?access_token=effff68dbeb5f9fc0d2df20cb51bffa266748f2d177b730d5d096cb54b35e5f0
So in In[34] and In[35] (you have to scroll a lot) they use numpy polyfit to calculate the trend for given temperature data. However, I do not understand how to use it.
Can somebody explain it?
The question has been answered on Developerworks:-
https://developer.ibm.com/answers/questions/282350/how-does-numpy-polyfit-work.html
I will try to explain each of this:-
index = chile[chile>0.0].index => this statements gives out all the years which are indices in chile python series which are greater than 0.0.
fit = np.polyfit(index.astype('int'), chile[index].values,1)
This is polyfit function call which find out ploynomial fitting coefficient(slope and intercept) for the given x(years) and y(precipitation on year) values at index(years) supplied through the vectors.
print "slope: " + str(fit[0])
The below code simply plots the datapoints referenced to straight line to show the trend
plt.plot(index, chile[index],'.')
Perticularly in the below statement the second argument is actually straight line equation to represent y which is "y = mx + b" where m is the slope and b is intercept that we found out above using polyfit.
plt.plot(index, fit[0]*index.astype('int') + fit[1], '-', color='red')
plt.title("Precipitation Trend for Chile")
plt.xlabel("Year")
plt.ylabel("Precipitation (million cubic meters)")
plt.show()
I hope that helps.
Thanks, Charles.

how to shift x axis labesl on line plot?

I'm using pandas to work with a data set and am tring to use a simple line plot with error bars to show the end results. It's all working great except that the plot looks funny.
By default, it will put my 2 data groups at the far left and right of the plot, which obscures the error bar to the point that it's not useful (the error bars in this case are key to intpretation so I want them plainly visible).
Now, I fix that problem by setting xlim to open up some space on either end of the x axis so that the error bars are plainly visible, but then I have an offset from where the x labels are to where the actual x data is.
Here is a simplified example that shows the problem:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df6 = pd.DataFrame( [-0.07,0.08] , index = ['A','B'])
df6.plot(kind='line', linewidth=2, yerr = [ [0.1,0.1],[0.1,0.1 ] ], elinewidth=2,ecolor='green')
plt.xlim(-0.2,1.2) # Make some room at ends to see error bars
plt.show()
I tried to include a plot (image) showing the problem but I cannot post images yet, having just joined up and do not have anough points yet to post images.
What I want to know is: How do I shift these labels over one tick to the right?
Thanks in advance.
Well, it turns out I found a solution, which I will jsut post here in case anyone else has this same issue in the future.
Basically, it all seems to work better in the case of a line plot if you just specify both the labels and the ticks in the same place at the same time. At least that was helpful for me. It sort of forces you to keep the length of those two lists the same, which seems to make the assignment between ticks and labels more well behaved (simple 1:1 in this case).
So I coudl fix my problem by including something like this:
plt.xticks([0, 1], ['A','B'] )
right after the xlim statement in code from original question. Now the A and B align perfectly with the place where the data is plotted, not offset from it.
Using above solution it works, but is less good-looking since now the x grid is very coarse (this is purely and aesthetic consideration). I could fix that by using a different xtick statement like:
plt.xticks([-0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0], ['','A','','','','','B',''])
This gives me nice looking grid and the data where I need it, but of course is very contrived-looking here. In the actual program I'd find a way to make that less clunky.
Hope that is of some help to fellow seekers....

Interactive image plotting with matplotlib

I am transitioning from Matlab to NumPy/matplotlib. A feature in matplotlib that seems to be lacking is interactive plotting. Zooming and panning is useful, but a frequent use case for me is this:
I plot a grayscale image using imshow() (both Matlab and matplotlib do well at this). In the figure that comes up, I'd like to pinpoint a certain pixel (its x and y coordinates) and get its value.
This is easy to do in the Matlab figure, but is there a way to do this in matplotlib?
This appears to be close, but doesn't seem to be meant for images.
custom event handlers are what you are going to need for this. It's not hard, but it's not "it just works" either.
This question seems pretty close to what you are after. If you need any clarification, I'd be happy to add more info.
I'm sure you have managed to do this already. Slightly(!) modifying the link, I've written the following code that gives you the x and y coordinates once clicked within the drawing area.
from pylab import *
import sys
from numpy import *
from matplotlib import pyplot
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def __call__(self,event):
if event.inaxes:
print("Inside drawing area!")
print("x: ", event.x)
print("y: ", event.y)
else:
print("Outside drawing area!")
if __name__ == '__main__':
x = range(10)
y = range(10)
fig = pyplot.figure("Test Interactive")
pyplot.scatter(x,y)
test = Test(x,y)
connect('button_press_event',test)
pyplot.show()
Additionally, this should make it easier to understand the basics of interactive plotting than the one provided in the cookbook link.
P.S.: This program would provide the exact pixel location. The value at that location should give us the grayscale value of respective pixel.
Also the following could help:
http://matplotlib.sourceforge.net/users/image_tutorial.html

matplotlib: working with range in x-axis

I'm trying to do a basic line graph here, but I can't seem to figure out how to adjust my x axis.
And here is the error I get when I try adjusting my range.
from pylab import *
plot ( range(0,11),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' )
plot ( range(0,11),[12,5,33,2,4,5,3,3,22,10],'o-',label='sample2' )
xlabel('x axis')
ylabel('y axis')
title('my sample graphs')
legend(('sample1','sample2'))
savefig("sampleg.png",dpi=(640/8))
show()
File "C:\Python26\lib\site-packages\matplotlib\axes.py", line 228, in _xy_from_xy
raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension
I want my range to be a list of strings: ["12/1/2007","12/1/2008", "12/1/2009","12/1/2010"]
Any suggestions?
Honestly, I found the code online and was trying to rewrite it to properly understand it. I think I'm going to start from scratch so that I know what I'm doing but I need help on where to start.
I posted another question which explains what I want to do here:
Using PyLab to create a 2D graph from two separate lists
range(0,11) should be range(0,10).
In addition to Steve's observation: If your points are always some y-value at the same consecutive integer x's, matplotlib makes the range even implicit.
plot([9,4,5,2,3,5,7,12,2,3],'.-',label='sample1')