I am new with matplotlib and I am trying to make an animation of a list of grib files.
I wrote this code:
import pygrib
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import os
m = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
lat_0=0, lon_0=-130)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
for grib in os.listdir("path"):
grbs=pygrib.open(grib)
for grb in grbs:
print grb
lats, lons = grb.latlons()
data=grb.values
x, y = m(lons,lats)
norm=colors.LogNorm())
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
cmap = plt.get_cmap('YlOrBr')
cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
plt.colorbar(cs,orientation='vertical', shrink=0.3)
plt.show()
and it works opening a windows that I have to close and after this opening a new one.
I want to use a nice animation with matplotlib.animation : i would change the grib over a map and showing it as a time series.
I try this:
m = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
lat_0=0, lon_0=-130)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
#reading the gribs files
griblist = os.listdir("path")
def animate (i):
global griblist
for grib in griblist:
grbs=pygrib.open(grib)
for grb in grbs:
grb
lats, lons = grb.latlons()
x, y = m(lons, lats)
data = grb.values
cmap = plt.get_cmap('YlOrBr')
cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
plt.colorbar(cs,orientation='vertical', shrink=0.5)
plt.title('UV biological effective dose')
anim = animation.FuncAnimation(plt.gcf(), animate,
frames=len(os.listdir("/home/gloria/UV_CAMS")), interval=500, blit=True)
plt.show()
But I got this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
return self.func(*args)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 590, in callit
func(*args)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 373, in idle_draw
self.draw()
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 354, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 474, in draw
self.figure.draw(self.renderer)
File "/usr/lib/python2.7/dist-packages/matplotlib/artist.py", line 61, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/figure.py", line 1165, in draw
self.canvas.draw_event(renderer)
File "/usr/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 1809, in draw_event
self.callbacks.process(s, event)
File "/usr/lib/python2.7/dist-packages/matplotlib/cbook.py", line 563, in process
proxy(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/cbook.py", line 430, in __call__
return mtd(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 648, in _start
self._init_draw()
File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 1193, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 1214, in _draw_frame
for a in self._drawn_artists:
TypeError: 'NoneType' object is not iterable
What I got if that I need to tell Python to iterate thought some variable using the function animate().
I am not fluent with defining functions and I am stuck in this part of the code: I cannot understand where my code is wrong...
Some help about this?
Many thanks!!
To get rid of the error, set blit=False.
Apart the animation would currently not animate anything because for each frame you loop over all files. Instead you want to show one file per frame.
griblist = os.listdir("path")
def animate (i):
grib = griblist[i]
grbs=pygrib.open(grib)
lats, lons = grb.latlons()
x, y = m(lons, lats)
data = grb.values
cmap = plt.get_cmap('YlOrBr')
cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
plt.colorbar(cs,orientation='vertical', shrink=0.5)
plt.title('UV biological effective dose')
anim = animation.FuncAnimation(plt.gcf(), animate,
frames=len(griblist), interval=500)
plt.show()
Related
I have a matplotlib plot with a slider and am interested in setting the colors of the points plotted as the slider gets dragged one way or the other. I know you can set the colors of points with set_array() but so far have had luck passing set_array() only 1D arrays of floats. When I pass set_array() an array of strings corresponding to matplotlib colors, I receive the error and traceback below.
Here are some relevant code snippets, with dummy info. for ease of assessment. With the two commented-out lines in update(val), the error below appears. Un-commenting them, so that set_array() gets a float, fixes the issue, but then I lose ability to control the colors with any precision. (For instance, changing 'g' to 'c' makes no perceptible difference in the colors.)
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import matplotlib.colors as c
x = np.linspace(1, 100, 100)
y = x**2
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.20)
plt.ylim([y.min(), y.max()])
plt.xlim([0, 100])
init = 4
scat = ax.scatter(x[:init], y[:init], s=5, c=['k']*init)
ax_slider = plt.axes([0.15, 0.05, 0.65, 0.03])
slider = Slider(ax_slider, 'Day', 0, 100, valinit=init, valfmt="%i")
# Update function, called upon slider movement
def update(val):
val = int(val)
colors_new = np.array(['k']*val, dtype=object)
colors_new[::2] = 'g'
colors_new[1::2] = 'm'
# colors_new = map(lambda x: c.to_rgb(x), colors_new)
# colors_new = np.dot(colors_new, [0.2989, 0.5870, 0.1140])
scat.set_array(colors_new)
xx = np.vstack((x[:val], y[:val]))
scat.set_offsets(xx.T)
# Call update function on slider value change
slider.on_changed(update)
plt.show()
Traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
return self.func(*args)
File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 531, in callit
func(*args)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/backends/_backend_tk.py", line 310, in idle_draw
self.draw()
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 12, in draw
super(FigureCanvasTkAgg, self).draw()
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 437, in draw
self.figure.draw(self.renderer)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/figure.py", line 1493, in draw
renderer, self, artists, self.suppressComposite)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2635, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/collections.py", line 911, in draw
Collection.draw(self, renderer)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/collections.py", line 264, in draw
self.update_scalarmappable()
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/collections.py", line 808, in update_scalarmappable
self._facecolors = self.to_rgba(self._A, self._alpha)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/cm.py", line 274, in to_rgba
x = self.norm(x)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/colors.py", line 943, in __call__
self.autoscale_None(result)
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/matplotlib/colors.py", line 994, in autoscale_None
self.vmin = A.min()
File "/Users/johnsmith/PycharmProjects/LawSchoolData/venv/lib/python2.7/site-packages/numpy/ma/core.py", line 5602, in min
axis=axis, out=out, **kwargs).view(type(self))
AttributeError: 'str' object has no attribute 'view'
set_array() only works to set the color values when the color is defined by a colormap. You could create a custom ListedColormap and set the values numerically.
If you want to set the colors via color values, you can use set_facecolors():
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
x = np.linspace(1, 100, 100)
y = x**2
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.20)
plt.ylim([y.min(), y.max()])
plt.xlim([0, 100])
init = 4
scat = ax.scatter(x[:init], y[:init], s=5, c=['k']*init)
ax_slider = plt.axes([0.15, 0.05, 0.65, 0.03])
slider = Slider(ax_slider, 'Day', 0, 100, valinit=init, valfmt="%i")
# Update function, called upon slider movement
def update(val):
val = int(val)
colors_new = np.array(['k']*val, dtype=object)
colors_new[::2] = 'g'
colors_new[1::2] = 'm'
scat.set_facecolors(colors_new)
xx = np.vstack((x[:val], y[:val]))
scat.set_offsets(xx.T)
# Call update function on slider value change
slider.on_changed(update)
plt.show()
Here is an example working with a colormap:
colors = ['k', 'g', 'm']
cmap = ListedColormap(colors)
scat = ax.scatter(x[:init], y[:init], s=5, c=np.zeros(init), cmap=cmap, vmin=0, vmax=len(colors)-1)
#....
def update(val):
val = int(val)
colors_new = np.zeros(val)
colors_new[::2] = 1
colors_new[1::2] = 2
scat.set_array(colors_new)
#....
I am new to python so I understand that this may be a stupid question, but I am having issues animating this. I can't see what the error is. I get this error
TypeError: f() missing 1 required positional argument: '
I want to use matplotlib when animating, because I have not downloaded scitools.
Any help at all would be very much appriciated
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
x = np.linspace(-6, 6)
tmax = 1
tmin = -1
t = np.linspace(-1, 1)
def f(x, t):
term = (np.exp(-1*(x-3*t)**2))*np.sin(3*np.pi*(x-t))
return term
max_f = f(x[-1], t[-1])
plt.ion()
y = f(x, tmax)
lines = plt.plot(x, y)
plt.axis([x[0], x[-1], -0.1, max_f])
plt.xlabel('x')
plt.ylabel('f')
counter = 0
for ts in t:
y = f(x, t)
lines[0].set_ydata(y)
plt.legend(['ts=%4.2f' % ts])
plt.draw()
plt.savefig('tmp_%04d.png' % counter)
counter += 1
fig = plt.figure()
anim = animation.FuncAnimation(fig, f, interval = 1000, blit=True)
fig = plt.figure()
plt.axis([x[0], x[-1], -0.1, max_f])
lines = plt.plot([], [])
plt.xlabel('x')
plt.ylabel('f')
plt.show()
EDIT, full traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 1699, in call
return self.func(*args)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 745, in callit
func(*args)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 370, in idle_draw
self.draw()
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\figure.py", line 1151, in draw
self.canvas.draw_event(renderer)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backend_bases.py", line 1823, in draw_event
self.callbacks.process(s, event)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook.py", line 554, in process
proxy(*args, **kwargs)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook.py", line 416, in call
return mtd(*args, **kwargs)
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 881, in _start
self._init_draw()
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1540, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Users\me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1562, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
TypeError: f() missing 1 required positional argument: 't'
As said, this is not really about the error, you can easily prevent that by supplying some value for t as fargs in FuncAnimation. However, this will not lead to the code producing an animation at all and hence as said, start with the exmaple add your functions and code step by step and see what happens.
This will eventually lead to something like the following:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(-6, 6)
tmax = 1
tmin = -1
t = np.linspace(-1, 1)
def f(x, t):
term = (np.exp(-1*(x-3*t)**2))*np.sin(3*np.pi*(x-t))
return term
y = f(x, tmax)
lines = plt.plot(x, y)
plt.axis([x[0], x[-1], -1, 1])
plt.xlabel('x')
plt.ylabel('f')
counter = [0]
def animate(ts):
y = f(x, ts)
lines[0].set_ydata(y)
plt.legend(['ts=%4.2f' % ts])
#plt.savefig('tmp_%04d.png' % counter)
counter[0] += 1
anim = animation.FuncAnimation(plt.gcf(), animate, frames = t, interval = 1000)
plt.show()
I have the following code:
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import AutoMinorLocator
import matplotlib.ticker as ticker
import pylab as pl
import numpy as np
matplotlib.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica'], 'weight':'bold'})
from matplotlib.font_manager import fontManager, FontProperties
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Helvetica'
matplotlib.rcParams['mathtext.it'] = 'Helvetica:italic'
matplotlib.rcParams['mathtext.bf'] = 'Helvetica:bold'
font= FontProperties(weight='bold',size=18)
data = np.genfromtxt('data', names=True, dtype=None, usecols=("x", "y1", "y2", "y3"))
x = data['x']
n = data['y1']
j = data['y2']
v = data['y3']
minorLocator = AutoMinorLocator(2)
def format():
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(3)
for tick in ax.yaxis.get_ticklabels():
tick.set_fontsize(22)
tick.set_weight('bold')
for tick in ax.xaxis.get_ticklabels():
tick.set_fontsize(22)
tick.set_weight('bold')
ax.set_ylabel(r'$\mathrm{ \Delta{}E_{solv}^{imp}}$',fontsize=26,fontweight='bold')
ax.tick_params(axis='x', which='both', direction='in', length=10, width=3, pad=8, top='off')
ax.tick_params(axis='y', which='major', direction='in', length=10, width=3, pad=8, right='off')
ax.tick_params(axis='y', which='minor', direction='in', length=6, width=2, right='off')
fig = plt.figure(figsize=(9.6,12), dpi=300, linewidth=3.0)
ax = fig.add_subplot(211)
r=np.arange(1,25,1.5)
p1 = ax.bar(r,v,width=0.9,color='white',edgecolor='black', lw=1.0, align='center')
p2 = ax.bar(r,j,width=0.6,color='red',edgecolor='black', lw=1.0, align='center')
p3 = ax.bar(r,n,width=0.3,color='black',edgecolor='black', lw=1.0, align='center')
ax.set_xticks(r)
ax.set_xticklabels(x,rotation=45)
format()
plt.axhline(y=0,linewidth=1,color='black')
plt.axis([0.0,24.5,-0.36,0.15])
ax.yaxis.set_minor_locator(minorLocator)
pl.rc('axes',linewidth=3)
ax.xaxis.grid(True,which='major',color='gray', linestyle='--',linewidth=0.5)
ax.set_axisbelow(True)
data = np.genfromtxt('data-2', names=True, dtype=None, usecols=("x", "y1"))
x = data['x']
n = data['y1']
ax = fig.add_subplot(212)
r=np.arange(1,31,1.5)
p1 = ax.bar(r,v,width=0.9,color='red',edgecolor='black', lw=1.0, align='center')
ax.set_xticks(r)
ax.set_xticklabels(x,rotation=90)
format()
plt.axhline(y=0,linewidth=1,color='black')
plt.axis([0.0,30.5,-0.48,0.40])
for label in ax.xaxis.get_ticklabels():
label.set_horizontalalignment('center')
ax.yaxis.set_minor_locator(minorLocator)
pl.rc('axes',linewidth=3)
ax.xaxis.grid(True,which='major',color='gray',linestyle='--',linewidth=0.5)
ax.set_axisbelow(True)
fig.set_tight_layout(True) #tried plt.tight_layout() also. didn't work
plt.savefig('image.png',dpi=300,format='png', orientation='landscape')
I am not able to save plt.show() the graph. I get the following error. I still keep getting the same error even if I delete the fig.set_tight_layout(True) line. The reason for posting this whole code is that I am not able to reproduce the same error if I run part of the code.
Thank you for the help.
Traceback (most recent call last):
File "image.py", line 83, in <module>
plt.savefig('image.png',dpi=300,format='png', orientation='landscape')
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 576, in savefig
res = fig.savefig(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1470, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 2192, in print_figure
**kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 513, in print_png
FigureCanvasAgg.draw(self)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 461, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1079, in draw
func(*args)
File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2092, in draw
a.draw(renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1105, in draw
renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1054, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/text.py", line 741, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/text.py", line 320, in _get_layout
ismath=ismath)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 220, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/usr/local/lib/python2.7/site-packages/matplotlib/mathtext.py", line 3005, in parse
box = self._parser.parse(s, font_output, fontsize, dpi)
File "/usr/local/lib/python2.7/site-packages/matplotlib/mathtext.py", line 2339, in parse
six.text_type(err)]))
ValueError:
_
^
Expected "\" (at char 1), (line:1, col:2)
It was actually some math formatting related issue although not in ylabel. I do not know why but reentering all the list elements (containing several $A_a$) again worked.
I'm trying to plot a data set (777 x 576) with 3D contours. This appears to be working fine until I try to place the contour under the 3d plot.
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm, pyplot
import numpy
X,Y = numpy.mgrid[:len(data), :len(data[0])]
fig = pyplot.figure('''figsize=(20, 10), dpi=800''')
ax = fig.gca(projection='3d')
ax.plot_surface(X,
Y,
data,
rstride=100,
cstride=100,
alpha=0.3,
linewidths=(.5,),
antialiased=True,
)
# cset = ax.contourf(X, Y, data, zdir='z', offset=130, cmap=cm.coolwarm)
ax.set_xlim(800, 0)
ax.set_ylim(0, 600)
ax.set_zlim(130, 170)
plt.show()
That is to say that uncommenting the ax.contourf(...) line causes the following exception:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
self.show()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1034, in draw
func(*args)
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 248, in draw
for col in self.collections]
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\art3d.py", line 456, in do_3d_projection
cedge = cedge.repeat(len(xyzlist), axis=0)
ValueError: array is too big.
In case this means anything:
len(cedge) == 35656
len(xyzlist) == 8914
35656 * 8914 = 317837584
Is there something I need to set to accommodate my data set?
I'm trying to create an animation of my clustering where each cluster is a different color on a scatter plot and there are several clusters per plot. The next plot to show has the same clusters and colors but a different location.
I've searched around and so far have this (timePeriodData refers to a list of cluster objects. Each list contains the clusters for that time/plot and the cluster object has the x, y, and color data.):
plt.ion()
fig,ax = subplots(1,1)
ax.set_aspect('equal')
fig.canvas.draw()
background = fig.canvas.copy_from_bbox(ax.bbox)
for timeData in timePeriodData:
plt.clf()
#print timeperiod
for cluster in timeData:
#ax.scatter(cluster.dataX,cluster.dataY, color = cluster.color)
# restore background
plt.scatter(cluster.dataX,cluster.dataY, color = cluster.color)
#plt.show()
#fig.canvas.restore_region(background)
# redraw just the points
#ax.draw_artist()
# fill in the axes rectangle
#fig.canvas.blit(ax.bbox)
plt.draw()
time.sleep(1)
But the plot window eventually hangs and doesn't continue plotting after about 5 plots. You can see in the comments I also tried to save the background and update that, but I am doing something wrong there. What exactly needs to be updated confuses me and I can't find good documentation on what needs to be passed to draw_artist.
I've also tried to use the animation feature of matplotlib, but can't seem to get it working with what I am trying to do.
timeperiods = 4
fig, ax = plt.subplots()
#fig = plt.figure()
def update(timePeriod, *args):
clusterNum = 0
for cluster in args[timePeriod]:
scat = ax.scatter(cluster.dataX,cluster.dataY, color = cluster.color)
clusterNum +=1
#scat = ax.scatter(dataX, dataY, c = scalarMap.to_rgba(values[clusterNum]))
return scat
ani = animation.FuncAnimation(fig, update, frames=xrange(timeperiods),
fargs=(timePeriodData), blit = True)
plt.show()
It says something is not iterable, but I'm sure what part it is referring to. I'm also not sure if I can continually assign scat to ax.scatter and it will add the points or not. but I assume so. Error message is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
self.show()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1040, in draw
self.canvas.draw_event(renderer)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 1693, in draw_event
self.callbacks.process(s, event)
File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 527, in process
proxy(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 405, in __call__
return mtd(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 832, in _end_redraw
self._post_draw(None, self._blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 778, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 787, in _blit_draw
for a in artists:
TypeError: 'PathCollection' object is not iterable
Any help getting a working system would be great!