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.
Related
I am creating a grid of plots with matplotlib which uses astropy World Cordinate System projection.
I would like to complete clear one of the axis (no titles, labels or ticks) but I have not been able with the traditional commands.
This script reproduces the issues:
import matplotlib.pyplot as plt
from astropy.wcs import WCS
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
filename = get_pkg_data_filename('galactic_center/gc_msx_e.fits')
hdu = fits.open(filename)[0]
wcs = WCS(hdu.header)
ax = plt.subplot(projection=wcs)
ax.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower')
ax.grid(color='white', ls='solid')
ax.update({'xlabel': 'Galactic Longitude', 'ylabel': ''})
ax.yaxis.set_ticklabels([], minor=True)
ax.yaxis.set_major_locator(plt.NullLocator())
plt.show()
I wonder if anyone could please share any advice
Thank you.
UPDATE:
Following #Chang Ye solution, I have adapted the code to:
import matplotlib.pyplot as plt
from astropy.wcs import WCS
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
filename = get_pkg_data_filename('galactic_center/gc_msx_e.fits')
hdu = fits.open(filename)[0]
wcs = WCS(hdu.header)
ax = plt.subplot(projection=wcs[0])
ax.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower')
ax.grid(color='white', ls='solid')
ax.update({'xlabel': 'Galactic Longitude', 'ylabel': ''})
ax.yaxis.set_ticklabels([], minor=True)
ax.yaxis.set_major_locator(plt.NullLocator())
plt.show()
However, this script produces the following issue within astropy (the plot is stil displayed but without either the desired and non-desired axes features):
Traceback (most recent call last):
File "/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_qt.py", line 455, in _draw_idle
self.draw()
File "/anaconda3/lib/python3.8/site-packages/matplotlib/backends/backend_agg.py", line 436, in draw
self.figure.draw(self.renderer)
File "/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py", line 73, in draw_wrapper
result = draw(artist, renderer, *args, **kwargs)
File "/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "/anaconda3/lib/python3.8/site-packages/matplotlib/figure.py", line 2810, in draw
mimage._draw_list_compositing_images(
File "/anaconda3/lib/python3.8/site-packages/matplotlib/image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "/anaconda3/lib/python3.8/site-packages/astropy/visualization/wcsaxes/core.py", line 464, in draw
super().draw(renderer, **kwargs)
File "/anaconda3/lib/python3.8/site-packages/matplotlib/artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 3082, in draw
mimage._draw_list_compositing_images(
File "/anaconda3/lib/python3.8/site-packages/matplotlib/image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "/anaconda3/lib/python3.8/site-packages/astropy/visualization/wcsaxes/core.py", line 45, in draw
self.axes.draw_wcsaxes(renderer)
File "/anaconda3/lib/python3.8/site-packages/astropy/visualization/wcsaxes/core.py", line 414, in draw_wcsaxes
coord._draw_grid(renderer)
File "/anaconda3/lib/python3.8/site-packages/astropy/visualization/wcsaxes/coordinate_helpers.py", line 571, in _draw_grid
self._update_grid_lines_1d()
File "/anaconda3/lib/python3.8/site-packages/astropy/visualization/wcsaxes/coordinate_helpers.py", line 864, in _update_grid_lines_1d
x_ticks_pos = [a[0] for a in self.ticks.pixel['b']]
KeyError: 'b'
My astropy version is 5.0.4 and the matplotlib version is 3.5.1
The ticker and label do not change because the projection will fill default value when it is empty. You can set them into white space, for example, 'ylabel': ' '.
But changing projection definition from wcs into wcs[0] is the fastest way to creat figure you want.
ax = plt.subplot(projection=wcs[0])
Output:
I am trying to modify the plot shown in this answer, but replacing the fill_between with violin plots at each tick.
A naive implementation made me try following,
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.linspace(1,5,100)
y1 = np.ones(x.size)
y2 = np.ones(x.size)*2
y3 = np.ones(x.size)*3
z = np.sin(x/2)
plt.figure()
ax = plt.subplot(projection='3d')
ax.plot(x, y1, z, color='r')
ax.plot(x, y2, z, color='g')
ax.plot(x, y3, z, color='b')
handle = plt.violinplot(x)
ax.add_collection3d(handle, zs=1, zdir='y')
The error that pops up is: AttributeError: 'PolyCollection' object has no attribute 'do_3d_projection'.
The error origin can be traced by the following log:
runcell(7, 'Figure.py')
Traceback (most recent call last):
File "Figure.py", line 163, in <module>
ax.add_collection3d(handle, zs=1, zdir='y')
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 2252, in add_collection3d
super().add_collection(col)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\axes\_base.py", line 1921, in add_collection
label = collection.get_label()
AttributeError: 'dict' object has no attribute 'get_label'
Traceback (most recent call last):
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\formatters.py", line 341, in __call__
return printer(obj)
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\pylabtools.py", line 248, in <lambda>
png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\pylabtools.py", line 132, in print_figure
fig.canvas.print_figure(bytes_io, **kw)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\backend_bases.py", line 2193, in print_figure
self.figure.draw(renderer)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\artist.py", line 41, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\figure.py", line 1864, in draw
renderer, self, artists, self.suppressComposite)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\image.py", line 131, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\artist.py", line 41, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 447, in draw
reverse=True)):
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 446, in <lambda>
key=lambda col: col.do_3d_projection(renderer),
AttributeError: 'PolyCollection' object has no attribute 'do_3d_projection'
<Figure size 432x288 with 1 Axes>
Also tried using individual body objects using plt.violinplot(x)['objects'][i] but the same error is returned.
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 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()
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?