Unable to save Figure in iPython Notebook throwing KeyError - python

I am trying to save an eps file using savefig method of matplotlib, but I am getting an unusual exception (KeyError), and the message isn't actionable. Let me know what can be done thanks.
Regards,
Harsh
data_for_x_axis = [0,30,60,90,120,150,180]
data_for_y_axis = [0, 0.1, 0.2, 0.3, 0.2, 0.1, 0]
AX1 = plt.subplot(221)
plt.margins(1)
AX1.cla()
AX1.plot(data_for_x_axis, data_for_y_axis) # some data
AX1.set_xlim([0,180])
AX1.set_xticks([0,30,60,90,120,150,180])
AX1.set_yticks([0.5,1])
AX1.set_title(r'Normalized Stokes $I$')
AX1.set_xlabel('CQWP Rotation Angle (Degrees)')
AX1.set_ylabel(r'$I/I_{mean}$')
plt.savefig('.\\Plots\\4_ModDemod.eps', format='eps', dpi=2400)
This throws the following exception
xception in Tkinter callback
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/_backend_tk.py", line 256, in resize
self._tkcanvas.create_image(
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/backend_tkagg.py", line 9, in draw
super(FigureCanvasTkAgg, self).draw()
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 388, in draw
self.figure.draw(self.renderer)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/figure.py", line 1709, in draw
renderer, self, artists, self.suppressComposite)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/image.py", line 135, in _draw_list_compositing_images
a.draw(renderer)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 2605, in draw
artists.remove(spine)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 2554, in _update_title_position
# this happens for an empty bb
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/text.py", line 890, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/text.py", line 298, in _get_layout
clean_line, self._fontproperties, ismath=ismath)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py", line 206, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/mathtext.py", line 3362, in parse
font_output = fontset_class(prop, backend)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/mathtext.py", line 883, in __init__
self.cm_fallback = StixSansFonts(*args, **kwargs)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/mathtext.py", line 984, in __init__
fullpath = findfont(name)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/font_manager.py", line 1238, in findfont
rc_params)
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/font_manager.py", line 1270, in _findfont_cached
+ self.score_size(prop.get_size(), font.size))
File "/Volumes/Elements/SSP Data Reduction/env/lib/python3.7/site-packages/matplotlib/font_manager.py", line 1151, in score_weight
w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1]
KeyError: '1'

Related

matplotlib: latex: savefig: OSError no such file or directory

I am generating some png figures with python 2.7.3 and Agg backend and using the options:
matplotlib.rc('font', family = 'serif', serif = 'cm10', size = 19)
matplotlib.rc('text', usetex = True)
matplotlib.rcParams['text.latex.preamble'] = [r'\boldmath']
matplotlib.rcParams['font.weight'] = 'bold'
matplotlib.rcParams['axes.linewidth'] = 2
for the labels and titles in the figures. the code works fine when I run it on my cluster on a login node. When I submit it to a computing node I get
Traceback (most recent call last):
File "main.py", line 312, in <module>
main()
File "plotvoigt.py", line 97, in main
plt.savefig(savefilename, format = 'png')
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/pyplot.py", line 696, in savefig
res = fig.savefig(*args, **kwargs)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/figure.py", line 1563, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 2232, in print_figure
**kwargs)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 527, in print_png
FigureCanvasAgg.draw(self)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 474, in draw
self.figure.draw(self.renderer)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/figure.py", line 1159, in draw
func(*args)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2319, in draw
a.draw(renderer)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/axis.py", line 1110, in draw
renderer)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/axis.py", line 1060, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/text.py", line 961, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/text.py", line 352, in _get_layout
ismath=False)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 229, in get_text_width_height_descent
renderer=self)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/texmanager.py", line 678, in get_text_width_height_descent
page = next(iter(dvi))
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/dviread.py", line 89, in __iter__
have_page = self._read()
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/dviread.py", line 150, in _read
self._dispatch(byte)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/dviread.py", line 233, in _dispatch
self._fnt_def(k, c, s, d, a, l, n)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/dviread.py", line 388, in _fnt_def
tfm = _tfmfile(fontname)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/dviread.py", line 897, in _tfmfile
return _fontfile(texname, Tfm, '.tfm', _tfmcache)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/dviread.py", line 887, in _fontfile
filename = find_tex_file(texname + suffix)
File "/path/Python/2.7.3/lib/python2.7/site-packages/matplotlib/dviread.py", line 868, in find_tex_file
stderr=subprocess.PIPE)
File "/path/Python/2.7.3/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/path/Python/2.7.3/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
but then if I remove these matplotlib options and I remove the labels the figures are saved on the computing node without a problem.
How can I use latex for typesetting the figures on the computing node?

Axes without labels and only one plot produced instead of many using matplotlib with LateX

I am testing a python code which produces some plots from a database results using matplotlib with LateX. The problem is that I am getting only one plot and it is not labeled. Below the error and the lines of code that generates the error(I can post the whole method if needed).Any hint?
if fileName is not None:
if verbose:
print("Saving file")
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages(fileName) as pdf:
for fig in figures:
for ax in fig.axes:
__add_legend(ax, outside=legend_outside)
pdf.savefig(fig)
return figures
__add_legend is given by the following
def __add_legend(ax, handles=None, labels=None, alpha=0.5,
outside=None, loc='best', *args, **kwargs):
if not handles:
handles, labels = ax.get_legend_handles_labels()
if not handles:
return
if outside is not None and len(handles) >= outside:
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(handles, labels, loc='center left', fancybox=False,
frameon=False, shadow=False,
bbox_to_anchor=(1, 0.5)).draggable(True)
else:
ax.legend(handles, labels, loc=loc, fancybox=True,
shadow=True).draggable(True)
The error message
Traceback (most recent call last):
File "../plot_prog.py", line 5, in <module>
run_program()
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1364, in run_program
else filteritr_convergent)
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1285, in genPDFBooklet
pdf.savefig(fig)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends /backend_pdf.py", line 2473, in savefig
figure.savefig(self, format='pdf', **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1563, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 2232, in print_figure
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 2536, in print_pdf
self.figure.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1159, in draw
func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2319, in draw
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axis.py", line 1113, in draw
tick.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axis.py", line 254, in draw
self.label1.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/text.py", line 792, in draw
mtext=mtext)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 1912, in draw_tex
self._setup_textpos(curx, cury, angle, oldx, oldy)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 1770, in _setup_textpos
self.file.output(x - oldx, y - oldy, Op.textpos)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 589, in output
self.write(fill([pdfRepr(x) for x in data]))
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 149, in pdfRepr
raise ValueError("Can only output finite numbers in PDF")
ValueError: Can only output finite numbers in PDF
I used pdb command in python just before pdf.savefigs() and I obtained this
> /home/hammouc/Documents/mimclib-last/mimclib /plot.py(1287)genPDFBooklet()
-> pdf.savefig(fig)
(Pdb)
Traceback (most recent call last):
File "../plot_prog.py", line 5, in <module>
run_program()
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1367, in run_program
else filteritr_convergent)
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1287, in genPDFBooklet
pdf.savefig(fig)
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1287, in genPDFBooklet
pdf.savefig(fig)
File "/usr/lib/python2.7/bdb.py", line 48, in trace_dispatch
return self.dispatch_line(frame)
File "/usr/lib/python2.7/bdb.py", line 67, in dispatch_line
if self.quitting: raise BdbQuit bdb.BdbQuit

Writing axes titles with units raised to negative powers in matplotlib with TeX and matching formatting

I'm writing a lab report for uni and have decided to use pyplot to draw a graph for it. The units for one of my axes is V^(-1), but I can't seem to get matplotlib to write that with the power in superscript (it only superscripts the minus sign) when using the code:
plt.xlabel('$1/U (10^5 V ^-1 )$')
I'd also like to match the fonts used for the axes titles with that used for the values on the axes if at all possible. I've tried putting:
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
at the beginning of my code, but that gives me the error:
File "C:\Users\Sam\Documents\Uni\Labs\pytry.py", line 92, in <module>
plt.savefig("Xrayplot.png")
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.py", line 561, in savefig
return fig.savefig(*args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.py", line 1421, in savefig
self.canvas.print_figure(*args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wxagg.py", line 85, in print_figure
FigureCanvasAgg.print_figure(self, filename, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backend_bases.py", line 2220, in print_figure
**kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 505, in print_png
FigureCanvasAgg.draw(self)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.py", line 1034, in draw
func(*args)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes.py", line 2086, in draw
a.draw(renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axis.py", line 1089, in draw
renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axis.py", line 1038, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\text.py", line 753, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\text.py", line 320, in _get_layout
ismath=False)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 205, in get_text_width_height_descent
renderer=self)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\texmanager.py", line 666, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\texmanager.py", line 413, in make_dvi
'LaTeX: \n\n' % repr(tex)) + report)
RuntimeError: LaTeX was not able to process the following string:
'lp'
Here is the full report generated by LaTeX:
Any help would be much appreciated.
For the superscript add { } around the text that should be super scripted. For the fonts i don't know the solution.
plt.xlabel('$1/U (10^5 V ^{-1} )$')

Matplotlib - Float to HH:MM

Evening all,
I'm trying to produce yaxis as HH:MM. I thought using the two below #'d lines would do the trick but they produce the error which can be seen below. Any help greatly appreciated.
x = ['23/09/2013', '24/09/2013', '25/09/2013', '26/09/2013', '27/09/2013']
ytemp = ['03:04:54', '03:26:29', '03:41:13', '03:20:07', '01:01:04']
import datetime
from matplotlib.dates import date2num, MINUTES_PER_DAY, SEC_PER_DAY, DateFormatter
import pylab as p
# function: Represent a string time in seconds.
def convert(s):
h,m,s = map(float, s.split(':'))
return h/24. + m/MINUTES_PER_DAY + s/SEC_PER_DAY
for i in ytemp:
y.append(convert(str(i)))
fig = p.figure()
ax = fig.add_subplot(111)
N = len(y)
ind = range(N)
ax.bar(ind, y, facecolor='#777777', align='center')
#ax.yaxis_date()
#ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.set_ylabel('Idle Time')
ax.set_title(totalidle[1][0],fontstyle='italic')
ax.set_xticks(ind)
ax.set_xticklabels([x[0], x[1], x[2], x[3], x[4]])
fig.autofmt_xdate()
p.show()
y is [0.12840277777777775, 0.1433912037037037, 0.15362268518518518, 0.13896990740740742, 0.0424074074074074]
the error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
self.show()
File "C:\Python33\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "C:\Pytho Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
self.show()
File "C:\Python33\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "C:\Python33\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python33\lib\site-packages\matplotlib\artist.py", line 56, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python33\lib\site-packages\matplotlib\figure.py", line 1035, in draw
func(*args)
File "C:\Python33\lib\site-packages\matplotlib\artist.py", line 56, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python33\lib\site-packages\matplotlib\axes.py", line 2088, in draw
a.draw(renderer)
File "C:\Python33\lib\site-packages\matplotlib\artist.py", line 56, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 1092, in draw
ticks_to_draw = self._update_ticks(renderer)
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 946, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 946, in <listcomp>
tick_tups = [t for t in self.iter_ticks()]
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 890, in iter_ticks
majorLocs = self.major.locator()
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 802, in __call__
self.refresh()
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 819, in refresh
dmin, dmax = self.viewlim_to_dt()
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 564, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 311, in num2date
return _from_ordinalf(x, tz)
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 214, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1n33\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python33\lib\site-packages\matplotlib\artist.py", line 56, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python33\lib\site-packages\matplotlib\figure.py", line 1035, in draw
func(*args)
File "C:\Python33\lib\site-packages\matplotlib\artist.py", line 56, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python33\lib\site-packages\matplotlib\axes.py", line 2088, in draw
a.draw(renderer)
File "C:\Python33\lib\site-packages\matplotlib\artist.py", line 56, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 1092, in draw
ticks_to_draw = self._update_ticks(renderer)
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 946, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 946, in <listcomp>
tick_tups = [t for t in self.iter_ticks()]
File "C:\Python33\lib\site-packages\matplotlib\axis.py", line 890, in iter_ticks
majorLocs = self.major.locator()
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 802, in __call__
self.refresh()
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 819, in refresh
dmin, dmax = self.viewlim_to_dt()
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 564, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 311, in num2date
return _from_ordinalf(x, tz)
File "C:\Python33\lib\site-packages\matplotlib\dates.py", line 214, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
The ordinal error is resolved by implementing:
ax.set_ylim(bottom = 733681, top = 733682)
then the #'d out lines work fine.

matplotlib bug in plot_dates?

Just wanted to see if others thought that the following behaviour in matplotlib plot_date was buggy, or if it's just something I should put up with.
I have a multi-panel plot that I set up with sharex to facilitate zoom/pan on all axes, and I plot time series data in both panels. However, in the second panel, all of the data happens to be invalid (in this example I mask it).
from matplotlib.pyplot import figure,show
from datetime import datetime,timedelta
from numpy import sin,cos,linspace,pi,ma,array
fig=figure(figsize=(16,9))
ax1=fig.add_subplot(211)
ax2=fig.add_subplot(212,sharex=ax1)
# xdata is seconds
xdata=linspace(0,9999,10000)
tdata=array([datetime(2000,1,1)+timedelta(seconds=ss) for ss in xdata])
data1=ma.masked_array(sin(pi*xdata/300),mask=False)
data2=ma.masked_array(cos(pi*xdata/300),mask=True)
ax1.plot_date(tdata,data1,marker='',color='r')
ax2.plot_date(tdata,data2,marker='',color='b')
show()
I'd expect (prefer) it to just show up a blank panel, not to fail and give me a long unhelpful traceback. Is this the expected behaviour?
Notes:
This script also fails if I use ax.plot(...) instead of ax.plot_date(...)
It works fine (i.e. gives me an empty panel) if I just plot against xdata, not the datetime array tsdata (but I have to use ax1.set_xlim(xdata[0],xdata[-1]) to get a sensible domain displayed):
ax1.plot(xdata,data1,marker='',color='r')
ax2.plot(xdata,data2,marker='',color='b')
ax1.set_xlim(xdata[0],xdata[-1])
show()
I have just realised I can rescue the above plot by forcing the ax2 limits right before the show() command. I still think that the failure in the main example is inelegant:
ax2.set_xlim(tdata[0],tdata[-1])
show()
What do the experts think?
Thanks!
F.Y.I., This was on matplotlib 1.1.0, compiled from source on my PC.
Here is the traceback that I get:
Traceback (most recent call last):
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backendsbackend_gtk.py", line 395, in expose_even
self._render_figure(self._pixmap, w, h)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backends/backend_gtkagg.py", line 75, in _render_f
FigureCanvasAgg.draw(self)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 401, in draw
self.figure.draw(self.renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/figure.py", line 884, in draw
func(*args)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1983, in draw
a.draw(renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1036, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 926, in _update_ticks
tick_tups = [ t for t in self.iter_ticks()]
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 873, in iter_ticks
majorLocs = self.major.locator()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 749, in __call__
self.refresh()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 758, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 530, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 289, in num2date
if not cbook.iterable(x): return _from_ordinalf(x, tz)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 203, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev#scipy.org
Yes, I would call this a bug, or at least an oversight which looks like it has been fixed (via #ali_m https://github.com/matplotlib/matplotlib/issues/162).
I was getting this exception, but that was on a version of 1.3.x from June (my bad, thought I had a more current version on this computer). Current master does not have this problem and #ali_m reports that it also works on 1.2.1 and 1.3.0 so I suspect the fix is to upgrade you version of matplotlib.
What looks like is going on is that there isn't a check in the code that sorts out where to put the ticks has no check to make sure you have given in non-empty data.
The reason that setting the limits explicitly prevents the error is that the code never tries to figure out what the range of your empty data is.
Please create a github issue for this (and include the trace back in the issue).
In [7]: Traceback (most recent call last):
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4.py", line 366, in idle_draw
self.draw()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 148, in draw
FigureCanvasAgg.draw(self)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_agg.py", line 440, in draw
self.figure.draw(self.renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/figure.py", line 1027, in draw
func(*args)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axes.py", line 2088, in draw
a.draw(renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 1076, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 938, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 882, in iter_ticks
majorLocs = self.major.locator()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 785, in __call__
self.refresh()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 794, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 560, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 305, in num2date
return _from_ordinalf(x, tz)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 208, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1

Categories

Resources