Related
Using the python seaborn package I was trying to plot the nested bar graphs with three different y-axes as shown in the below figure:
And the code that I have used is :
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np
import seaborn as sns
#plt.style.use(['science'])
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)
HV = [388, 438]
YS = [1070, 1200]
UTS = [1150, 1400]
Z = [15, 12.5]
x = [1, 2]
fig, ax1 = plt.subplots(figsize=(5, 5.5))
colors=sns.color_palette("rocket",4)
ax1 = sns.barplot(x[0],YS[0],color="blue")
ax1 = sns.barplot(x[0],color="blue")
ax1 = sns.barplot(x[1],YS[1],color="blue")
ax1 = sns.barplot(x[1],UTS[1],color="blue")
ax2 = ax1.twinx()
ax2 = sns.barplot(x[0], HV[0],color="green")
ax2 = sns.barplot(x[1], HV[1],color="green")
ax3 = ax1.twinx()
ax3 = sns.barplot(x[0],Z[0],color="red")
ax3 = sns.barplot(x[1],Z[1],color="red")
#ax3.spines['right'].set_position(('outward',60))
ax3.spines['right'].set_position(('axes',1.15))
ax1.set_ylabel("First",color="blue")
ax2.set_ylabel("Second",color="green")
ax3.set_ylabel("Third",color="red")
ax1.tick_params(axis='y',colors="blue")
ax2.tick_params(axis='y',colors="green")
ax3.tick_params(axis='y',colors="red")
ax2.spines['right'].set_color("green")
ax3.spines['right'].set_color("red")
ax3.spines['left'].set_color("blue")
plt.show()
And I'm getting the following error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/seaborn/utils.py", line 531, in categorical_order
order = values.cat.categories
AttributeError: 'int' object has no attribute 'cat'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/seaborn/utils.py", line 534, in categorical_order
order = values.unique()
AttributeError: 'int' object has no attribute 'unique'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/sspenkulinti/these/thesis_E185_fatigue/test_matrix/E185_properties_AB_HT.py", line 21, in <module>
ax1 = sns.barplot(x[0],YS[0],color="blue")
File "/usr/lib/python3/dist-packages/seaborn/categorical.py", line 3147, in barplot
plotter = _BarPlotter(x, y, hue, data, order, hue_order,
File "/usr/lib/python3/dist-packages/seaborn/categorical.py", line 1614, in __init__
self.establish_variables(x, y, hue, data, orient,
File "/usr/lib/python3/dist-packages/seaborn/categorical.py", line 200, in establish_variables
group_names = categorical_order(groups, order)
File "/usr/lib/python3/dist-packages/seaborn/utils.py", line 536, in categorical_order
order = pd.unique(values)
File "/usr/lib/python3/dist-packages/pandas/core/algorithms.py", line 395, in unique
values = _ensure_arraylike(values)
File "/usr/lib/python3/dist-packages/pandas/core/algorithms.py", line 204, in _ensure_arraylike
inferred = lib.infer_dtype(values, skipna=False)
File "pandas/_libs/lib.pyx", line 1251, in pandas._libs.lib.infer_dtype
TypeError: 'int' object is not iterable
The error is because you can't call sns.barplot with a single number as first parameter. The x-values need to be a list.
To get want you want using seaborn, the data needs to be presented as if it comes from a dataframe. hue_order is needed to preserve enough space for each of the bars, even when nothing is plotted there.
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np
import seaborn as sns
HV = [388, 438]
YS = [1070, 1200]
UTS = [1150, 1400]
Z = [15, 12.5]
x = ["As built", "200ºC-850ºC"]
names = ['YS', 'UTS', 'HV', 'Z']
fig, ax1 = plt.subplots(figsize=(9, 5.5))
colors = sns.color_palette("tab10", len(names))
sns.barplot(x=x + x, y=YS + UTS, hue=[names[0]] * len(x) + [names[1]] * len(x),
hue_order=names, palette=colors, alpha=0.7, ax=ax1)
# ax1 will already contain the full legend, the third handle needs to
# be updated to show the hatching
ax1.legend_.legendHandles[2].set_hatch('///')
ax2 = ax1.twinx()
sns.barplot(x=x, y=HV, hue=[names[2]] * len(x), hue_order=names, palette=colors, hatch='//', alpha=0.7, ax=ax2)
ax2.legend_.remove() # seaborn automatically creates a new legend
ax3 = ax1.twinx()
sns.barplot(x=x, y=Z, hue=[names[3]] * len(x), hue_order=names, palette=colors, alpha=0.7, ax=ax3)
ax3.legend_.remove()
ax3.spines['right'].set_position(('axes', 1.15))
ax1.set_ylabel("First", color=colors[0])
ax2.set_ylabel("Second", color=colors[2])
ax3.set_ylabel("Third", color=colors[3])
ax1.tick_params(axis='y', colors=colors[0])
ax2.tick_params(axis='y', colors=colors[2])
ax3.tick_params(axis='y', colors=colors[3])
ax2.spines['right'].set_color(colors[2])
ax3.spines['right'].set_color(colors[3])
plt.tight_layout()
plt.show()
I want to draw a seaborn.heatmap and annotate only some rows/columns.
Example where all cells have annotation:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
n1 = 5
n2 = 10
M = np.random.random((n1, n2))
fig, ax = plt.subplots()
sns.heatmap(ax = ax, data = M, annot = True)
plt.show()
Following these examples (paragraph Adding Value Annotations), it is possible to pass to seaborn.heatmap an array with annotations for each cell as annot parameter:
annot : bool or rectangular dataset, optional
If True, write the data value in each cell. If an array-like with the same shape as data,
then use this to annotate the heatmap instead of the data.
Note that DataFrames will match on position, not index.
If I try to generate an array of str and pass it as annot parameter to seaborn.heatmap I get the following error:
Traceback (most recent call last):
File "C:/.../myfile.py", line 16, in <module>
sns.heatmap(ax = ax, data = M, annot = A)
File "C:\venv\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "C:\venv\lib\site-packages\seaborn\matrix.py", line 558, in heatmap
plotter.plot(ax, cbar_ax, kwargs)
File "C:\venv\lib\site-packages\seaborn\matrix.py", line 353, in plot
self._annotate_heatmap(ax, mesh)
File "C:\venv\lib\site-packages\seaborn\matrix.py", line 262, in _annotate_heatmap
annotation = ("{:" + self.fmt + "}").format(val)
ValueError: Unknown format code 'g' for object of type 'numpy.str_'
Code which generates the ValueError (in this case I try to remove annotations of the 4th columns as an example):
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
n1 = 5
n2 = 10
M = np.random.random((n1, n2))
A = np.array([[f'{M[i, j]:.2f}' for j in range(n2)] for i in range(n1)])
A[:, 3] = ''
fig, ax = plt.subplots(figsize = (6, 3))
sns.heatmap(ax = ax, data = M, annot = A)
plt.show()
What is the cause of this error?
How can I generate a seaborn.heatmap and annotate only selected rows/columns?
It is a formatting issue. Here the fmt = '' is required if you are using non-numeric labels (defaults to: fmt='.2g') which consider only for numeric values and throw an error for labels with text format.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
n1 = 5
n2 = 10
M = np.random.random((n1, n2))
A = np.array([[f'{M[i, j]:.2f}' for j in range(n2)] for i in range(n1)])
A[:, 3] = ''
fig, ax = plt.subplots(figsize = (6, 3))
sns.heatmap(ax = ax, data = M, annot = A, fmt='')
plt.show()
After defining ax1=fig1.add_subplot(111) and plotting 8 data series with associated label values, I used the following line of code to add a legend.
ax1.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
I have used this method many times before without a problem, but on this occasion it produces an error saying IndexError: tuple index out of range
Traceback (most recent call last):
File "interface_tension_adhesion_plotter.py", line 45, in <module>
ax1.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 564, in legend
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend.py", line 386, in __init__
self._init_legend_box(handles, labels, markerfirst)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend.py", line 655, in _init_legend_box
fontsize, handlebox))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend_handler.py", line 119, in legend_artist
fontsize, handlebox.get_transform())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/legend_handler.py", line 476, in create_artists
self.update_prop(coll, barlinecols[0], legend)
IndexError: tuple index out of range
I have no idea why this is happening and would really appreciate suggestions.
1. If data is intact and arrays are not empty, this code works perfectly.
fig = plt.gcf()
ax=fig.add_subplot(111)
for i in range(8):
x = np.arange(10)
y = i + random.rand(10)
yerr = .1*y
l = .1*i
ax.errorbar(x,y,yerr=yerr,label="adhsion={:02.1f}".format(l))
ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
2. I had same error when I applied a filter to my data and got empty arrays. This could be reproduced as follows:
fig = plt.gcf()
ax=fig.add_subplot(111)
for i in range(8):
x = np.arange(10)
y = i + random.rand(10)
yerr = .1*y
l = .1*i
if i == 7:
ind = np.isnan(y)
y = y[ind]
x = x[ind]
yerr = yerr[ind]
ax.errorbar(x,y,yerr=yerr,label="adhsion={:02.1f}".format(l))
ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
This code gives identical Traceback as in the question. Empty array for errors results in wrong handles for errorbars.
Workaround mentioned by #crevell:
handles, labels = ax.get_legend_handles_labels()
handles = [h[0] for h in handles]
ax.legend(handles, labels,loc='center left', bbox_to_anchor=(1.0, 0.5))
It works, but legend appears without errorbar lines.
So one should check the data supplied to the matplotlib errorbar function.
I search on internet how using a slider with 3D data and I find this algorithm which plot 3D data in 2D with a slider, so I copy-paste it and I tried to run it in order to adapt it (for solving my real problem : plotting 3D+time data and using a slider to interact with the time).
This is my complete code :
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
import scipy.ndimage as ndi
data = np.zeros((10, 10, 10))
data[5, 5, 5] = 10.
data = ndi.filters.gaussian_filter(data, sigma=1)
print(data.max())
def cube_show_slider(cube, axis=0, **kwargs):
"""
Display a 3d ndarray with a slider to move along the third dimension.
Extra keyword arguments are passed to imshow
"""
# check dim
if not cube.ndim == 3:
raise ValueError("cube should be an ndarray with ndim == 3")
# generate figure
fig = plt.figure()
ax = plt.subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
# select first image
s = [slice(0, 1) if i == axis else slice(None) for i in range(3)]
im = cube[s].squeeze()
# display image
l = ax.matshow(im, **kwargs)
cb = plt.colorbar(l)
cb.set_clim(vmin=data.min(), vmax=data.max())
cb.draw_all()
# define slider
axcolor = 'lightgoldenrodyellow'
ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
slideryo = Slider(ax, 'Axis %i index' % axis, 0, cube.shape[axis] - 1, valinit=0, valfmt='%i')
slideryo.on_changed(update)
plt.show()
def update(val):
ind = int(slider.val)
s = [slice(ind, ind + 1) if i == axis else slice(None) for i in range(3)]
im = cube[s].squeeze()
l.set_data(im, **kwargs)
cb.set_clim(vmin=data.min(), vmax=data.max())
cb.formatter.set_powerlimits((0, 0))
cb.update_ticks()
cb.draw_all()
fig.canvas.draw()
cube_show_slider(data)
A window with the axis and the slider are on my screen but no data is plotted. The plot is just a big blue square and when I interact with the slider I have this error :
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 1952, in motion_notify_event
self.callbacks.process(s, event)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/cbook.py", line 563, in process
proxy(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/cbook.py", line 430, in __call__
return mtd(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/widgets.py", line 434, in _update
self.set_val(val)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/widgets.py", line 448, in set_val
func(val)
File "<stdin>", line 2, in update
NameError: global name 'slider' is not defined
I don't understand why it doesn't work. All the functions and files that the console cite were added by the importation. And I know that the code written by mmensing is ok, so I missed something but what? I'm sure that I did a stupid error, but I don't know where.
To check if the data I created are ok, I write this code to see the 3d plot in 3D without slider :
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as ndi
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
data = np.zeros((10, 10, 10))
data[5, 5, 5] = 10.
data = ndi.filters.gaussian_filter(data, sigma=1)
ax.plot(data[0,:,:], data[1,:,:], data[2,:,:], label='my data')
ax.legend()
plt.show()
But it returns this error :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1541, in plot
lines = Axes.plot(self, xs, ys, *args[argsi:], **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/__init__.py", line 1812, in inner
return func(ax, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 1424, in plot
for line in self._get_lines(*args, **kwargs):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 386, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 339, in _plot_args
raise ValueError('third arg must be a format string')
ValueError: third arg must be a format string
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes/_axes.py:519: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.
warnings.warn("No labelled objects found. ")
What can I do ?
I have corrected your code, you had some errors which you can find by comparing:
update function needs to be defined in subprogram so that it is accessible there, indentation wrong
your slider had two different names at different positions
refer to update function only after having defined the function.
Hope it works now.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
import scipy.ndimage as ndi
data = np.zeros((10, 10, 10))
data[5, 5, 5] = 10.
data = ndi.filters.gaussian_filter(data, sigma=1)
print(data.max())
print data.shape
def cube_show_slider(cube, axis=0, **kwargs):
"""
Display a 3d ndarray with a slider to move along the third dimension.
Extra keyword arguments are passed to imshow
"""
# check dim
if not cube.ndim == 3:
raise ValueError("cube should be an ndarray with ndim == 3")
# generate figure
fig = plt.figure()
ax = plt.subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
# select first image
s = [slice(0, 1) if i == axis else slice(None) for i in range(3)]
im = cube[s].squeeze()
# display image
l = ax.matshow(im, **kwargs)
cb = plt.colorbar(l)
cb.set_clim(vmin=data.min(), vmax=data.max())
cb.draw_all()
# define slider
axcolor = 'lightgoldenrodyellow'
ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
slideryo = Slider(ax, 'Axis %i index' % axis, 0, cube.shape[axis] - 1, valinit=0, valfmt='%i')
def update(val):
ind = int(slideryo.val)
s = [slice(ind, ind + 1) if i == axis else slice(None) for i in range(3)]
im = cube[s].squeeze()
l.set_data(im, **kwargs)
cb.set_clim(vmin=data.min(), vmax=data.max())
cb.formatter.set_powerlimits((0, 0))
cb.update_ticks()
cb.draw_all()
fig.canvas.draw()
slideryo.on_changed(update)
plt.show()
cube_show_slider(data)
I have a 3D array of data (2 spatial dimensions and 1 time dimension) and I'm trying to produce an animated contour plot using matplotlib.animate. I'm using this link as a basis:
http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
And here's my attempt:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from numpy import array, zeros, linspace, meshgrid
from boutdata import collect
# First collect data from files
n = collect("n") # This is a routine to collect data
Nx = n.shape[1]
Nz = n.shape[2]
Ny = n.shape[3]
Nt = n.shape[0]
fig = plt.figure()
ax = plt.axes(xlim=(0, 200), ylim=(0, 100))
cont, = ax.contourf([], [], [], 500)
# initialisation function
def init():
cont.set_data([],[],[])
return cont,
# animation function
def animate(i):
x = linspace(0, 200, Nx)
y = linspace(0, 100, Ny)
x,y = meshgrid(x,y)
z = n[i,:,0,:].T
cont.set_data(x,y,z)
return cont,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
plt.show()
But when I do this, I get the following error:
Traceback (most recent call last):
File "showdata.py", line 16, in <module>
cont, = ax.contourf([], [], [], 500)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 7387, in contourf
return mcontour.QuadContourSet(self, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1112, in __init__
ContourSet.__init__(self, ax, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 703, in __init__
self._process_args(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1125, in _process_args
x, y, z = self._contour_args(args, kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1172, in _contour_args
x,y,z = self._check_xyz(args[:3], kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1204, in _check_xyz
raise TypeError("Input z must be a 2D array.")
TypeError: Input z must be a 2D array.
So I've tried replacing all the [] by [[],[]] but this then produces:
Traceback (most recent call last):
File "showdata.py", line 16, in <module>
cont, = ax.contourf([[],[]], [[],[]], [[],[]],500)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 7387, in contourf
return mcontour.QuadContourSet(self, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1112, in __init__
ContourSet.__init__(self, ax, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 703, in __init__
self._process_args(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1125, in _process_args
x, y, z = self._contour_args(args, kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/contour.py", line 1177, in _contour_args
self.zmax = ma.maximum(z)
File "/usr/lib/python2.7/dist-packages/numpy/ma/core.py", line 5806, in __call__
return self.reduce(a)
File "/usr/lib/python2.7/dist-packages/numpy/ma/core.py", line 5824, in reduce
t = self.ufunc.reduce(target, **kargs)
ValueError: zero-size array to maximum.reduce without identity
Thanks in advance!
Felix Schneider is correct about the animation becoming very slow. His solution of setting ax.collections = [] removes all old (and superseded) "artist"s. A more surgical approach is to only remove the artists involved in the drawing the contours:
for c in cont.collections:
c.remove()
which is useful in more complicated cases, in lieu of reconstructing the entire figure for each frame. This also works in Rehman Ali's example; instead of clearing the entire figure with clf() the value returned by contourf() is saved and used in the next iteration. Here is an example code similar to Luke's from Jun 7 '13, demonstrating removing the contours only:
import pylab as plt
import numpy
import matplotlib.animation as animation
#plt.rcParams['animation.ffmpeg_path'] = r"C:\some_path\ffmpeg.exe" # if necessary
# Generate data for plotting
Lx = Ly = 3
Nx = Ny = 11
Nt = 20
x = numpy.linspace(0, Lx, Nx)
y = numpy.linspace(0, Ly, Ny)
x,y = numpy.meshgrid(x,y)
z0 = numpy.exp(-(x-Lx/2)**2-(y-Ly/2)**2) # 2 dimensional Gaussian
def some_data(i): # function returns a 2D data array
return z0 * (i/Nt)
fig = plt.figure()
ax = plt.axes(xlim=(0, Lx), ylim=(0, Ly), xlabel='x', ylabel='y')
cvals = numpy.linspace(0,1,Nt+1) # set contour values
cont = plt.contourf(x, y, some_data(0), cvals) # first image on screen
plt.colorbar()
# animation function
def animate(i):
global cont
z = some_data(i)
for c in cont.collections:
c.remove() # removes only the contours, leaves the rest intact
cont = plt.contourf(x, y, z, cvals)
plt.title('t = %i: %.2f' % (i,z[5,5]))
return cont
anim = animation.FuncAnimation(fig, animate, frames=Nt, repeat=False)
anim.save('animation.mp4', writer=animation.FFMpegWriter())
This is what I got to work:
# Generate grid for plotting
x = linspace(0, Lx, Nx)
y = linspace(0, Ly, Ny)
x,y = meshgrid(x,y)
fig = plt.figure()
ax = plt.axes(xlim=(0, Lx), ylim=(0, Ly))
plt.xlabel(r'x')
plt.ylabel(r'y')
# animation function
def animate(i):
z = var[i,:,0,:].T
cont = plt.contourf(x, y, z, 25)
if (tslice == 0):
plt.title(r't = %1.2e' % t[i] )
else:
plt.title(r't = %i' % i)
return cont
anim = animation.FuncAnimation(fig, animate, frames=Nt)
anim.save('animation.mp4')
I found that removing the blit=0 argument in the FuncAnimation call also helped...
This is the line:
cont, = ax.contourf([], [], [], 500)
change to:
x = linspace(0, 200, Nx)
y = linspace(0, 100, Ny)
x, y = meshgrid(x, y)
z = n[i,:,0,:].T
cont, = ax.contourf(x, y, z, 500)
You need to intilize with sized arrays.
Here is another way of doing the same thing if matplotlib.animation don't work for you. If you want to continuously update the colorbar and everything else in the figure, use plt.ion() at the very beginning to enable interactive plotting and use a combo of plt.draw() and plt.clf() to continuously update the plot.
import matplotlib.pyplot as plt
import numpy as np
plt.ion(); plt.figure(1);
for k in range(10):
plt.clf(); plt.subplot(121);
plt.contourf(np.random.randn(10,10)); plt.colorbar();
plt.subplot(122,polar=True)
plt.contourf(np.random.randn(10,10)); plt.colorbar();
plt.draw();
Note that this works with figures containing different subplots and various types of plots (i.e. polar or cartesian)
I used Lukes approach (from Jun 7 '13 at 8:08 ), but added
ax.collections = []
right before
cont = plt.contourf(x, y, z, 25).
Otherwise I experienced that creating the animation will become very slow for large frame numbers.
I have been looking at this a while ago. I my situation I had a few subplots with contours which I wanted to animate. I did not want to use the plt.clf() solution as Rehman ali suggest as I used some special setup of my axis (with pi symbols etc) which would be cleaned as well, so I preferred the 'remove()' approach suggest be Felix. The thing is that only using 'remove' does not clean up memory and will clog your computer eventually, so you need to explicitly delete of the contours by setting it to an empty list as well.
In order to have a generic remove routine which is able to take away contours as well as text, I wrote the routine 'clean_up_artists' which you should use on every time step on all the axis.
This routine cleans up the artists which are passed in a list called 'artist_list' in a given axis 'axis'. This means that for animating multiple subplots, we need to store the lists of artists for each axis which we need to clean every time step.
Below the full code to animate a number of subplots of random data. It is pretty self-explanatory, so hopefully it becomes clear what happens. Anyhow, I just thought to post it, as it combines several ideas I found on stack overflow which I just to come up with this working example.
Anybody with suggestions to improve the code, please shoot-)
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.animation as animation
import string
import numpy as np
def clean_up_artists(axis, artist_list):
"""
try to remove the artists stored in the artist list belonging to the 'axis'.
:param axis: clean artists belonging to these axis
:param artist_list: list of artist to remove
:return: nothing
"""
for artist in artist_list:
try:
# fist attempt: try to remove collection of contours for instance
while artist.collections:
for col in artist.collections:
artist.collections.remove(col)
try:
axis.collections.remove(col)
except ValueError:
pass
artist.collections = []
axis.collections = []
except AttributeError:
pass
# second attempt, try to remove the text
try:
artist.remove()
except (AttributeError, ValueError):
pass
def update_plot(frame_index, data_list, fig, axis, n_cols, n_rows, number_of_contour_levels, v_min, v_max,
changed_artists):
"""
Update the the contour plots of the time step 'frame_index'
:param frame_index: integer required by animation running from 0 to n_frames -1. For initialisation of the plot,
call 'update_plot' with frame_index = -1
:param data_list: list with the 3D data (time x 2D data) per subplot
:param fig: reference to the figure
:param axis: reference to the list of axis with the axes per subplot
:param n_cols: number of subplot in horizontal direction
:param n_rows: number of subplot in vertical direction
:param number_of_contour_levels: number of contour levels
:param v_min: minimum global data value. If None, take the smallest data value in the 2d data set
:param v_max: maximum global data value. If None, take the largest value in the 2d data set
:param changed_artists: list of lists of artists which need to be updated between the time steps
:return: the changed_artists list
"""
nr_subplot = 0 # keep the index of the current subplot (nr_subplot = 0,1, n_cols x n_rows -1)
# loop over the subplots
for j_col in range(n_cols):
for i_row in range(n_rows):
# set a short reference to the current axis
ax = axis[i_row][j_col]
# for the first setup call, add and empty list which can hold the artists belonging to the current axis
if frame_index < 0:
# initialise the changed artist list
changed_artists.append(list())
else:
# for the next calls of update_plot, remove all artists in the list stored in changed_artists[nr_subplot]
clean_up_artists(ax, changed_artists[nr_subplot])
# get a reference to 2d data of the current time and subplot
data_2d = data_list[nr_subplot][frame_index]
# manually set the levels for better contour range control
if v_min is None:
data_min = np.nanmin(data_2d)
else:
data_min = v_min
if v_max is None:
data_max = np.nanmax(data_2d)
else:
data_max = v_max
# set the contour levels belonging to this subplot
levels = np.linspace(data_min, data_max, number_of_contour_levels + 1, endpoint=True)
# create the contour plot
cs = ax.contourf(data_2d, levels=levels, cmap=cm.rainbow, zorder=0)
cs.cmap.set_under("k")
cs.cmap.set_over("k")
cs.set_clim(v_min, v_max)
# store the contours artists to the list of artists belonging to the current axis
changed_artists[nr_subplot].append(cs)
# set some grid lines on top of the contours
ax.xaxis.grid(True, zorder=0, color="black", linewidth=0.5, linestyle='--')
ax.yaxis.grid(True, zorder=0, color="black", linewidth=0.5, linestyle='--')
# set the x and y label on the bottom row and left column respectively
if i_row == n_rows - 1:
ax.set_xlabel(r"Index i ")
if j_col == 0:
ax.set_ylabel(r"Index j")
# set the changing time counter in the top left subplot
if i_row == 0 and j_col == 1:
# set a label to show the current time
time_text = ax.text(0.6, 1.15, "{}".format("Time index : {:4d}".format(frame_index)),
transform=ax.transAxes, fontdict=dict(color="black", size=14))
# store the artist of this label in the changed artist list
changed_artists[nr_subplot].append(time_text)
# for the initialisation call only, set of a contour bar
if frame_index < 0:
# the first time we add this (make sure to pass -1 for the frame_index
cbar = fig.colorbar(cs, ax=ax)
cbar.ax.set_ylabel("Random number {}".format(nr_subplot))
ax.text(0.0, 1.02, "{}) {}".format(string.ascii_lowercase[nr_subplot],
"Random noise {}/{}".format(i_row, j_col)),
transform=ax.transAxes, fontdict=dict(color="blue", size=12))
nr_subplot += 1
return changed_artists
def main():
n_pixels_x = 50
n_pixels_y = 30
number_of_time_steps = 100
number_of_contour_levels = 10
delay_of_frames = 1000
n_rows = 3 # number of subplot rows
n_cols = 2 # number of subplot columns
min_data_value = 0.0
max_data_value = 1.0
# list containing the random plot per sub plot. Insert you own data here
data_list = list()
for j_col in range(n_cols):
for i_row in range(n_rows):
data_list.append(np.random.random_sample((number_of_time_steps, n_pixels_x, n_pixels_y)))
# set up the figure with the axis
fig, axis = plt.subplots(nrows=n_rows, ncols=n_cols, sharex=True, sharey=True, figsize=(12,8))
fig.subplots_adjust(wspace=0.05, left=0.08, right=0.98)
# a list used to store the reference to the axis of each subplot with a list of artists which belong to this subplot
# this list will be returned and will be updated every time plot which new artists
changed_artists = list()
# create first image by calling update_plot with frame_index = -1
changed_artists = update_plot(-1, data_list, fig, axis, n_cols, n_rows, number_of_contour_levels,
min_data_value, max_data_value, changed_artists)
# call the animation function. The fargs argument equals the parameter list of update_plot, except the
# 'frame_index' parameter.
ani = animation.FuncAnimation(fig, update_plot, frames=number_of_time_steps,
fargs=(data_list, fig, axis, n_cols, n_rows, number_of_contour_levels, min_data_value,
max_data_value, changed_artists),
interval=delay_of_frames, blit=False, repeat=True)
plt.show()
if __name__ == "__main__":
main()
Removing the blit=0 or blit = True argument in the FuncAnimation call also helped
is important!!!