Matplotlib - Float to HH:MM - python

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.

Related

Unable to save Figure in iPython Notebook throwing KeyError

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'

auto07p IndexError when uses matplotlib 2.0 instead of matplotlib 1.5

I am recently working on making auto07p work with matplotlib 2.0.
The source code can be found here:
https://sourceforge.net/projects/auto-07p/files/auto07p/0.9/
When using matplotlib 2.0 (or any version greater than 1.5), IndexError: invalid index to scalar variable. appears:
/home/ngb/auto/07p/python/Points.py:1086: VisibleDeprecationWarning: `rank` is deprecated; use the `ndim` attribute or function instead. To find the rank of a matrix see `numpy.linalg.matrix_rank`.
r = rank(array_temp)
Created plot
<graphics.windowPlotter.WindowPlotter2D object at 0x7f9e42007710>
AUTO> Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/usr/lib/python3.5/tkinter/__init__.py", line 608, in callit
func(*args)
File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 370, in idle_draw
self.draw()
File "/home/ngb/auto/07p/python/graphics/grapher_mpl.py", line 92, in draw
self.redraw()
File "/home/ngb/auto/07p/python/graphics/grapher_mpl.py", line 65, in redraw
FigureCanvasTkAgg.draw(self)
File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/figure.py", line 1143, in draw
renderer, self, dsu, self.suppressComposite)
File "/usr/lib/python3/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 2409, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/usr/lib/python3/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 1136, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 969, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 969, in <listcomp>
tick_tups = [t for t in self.iter_ticks()]
File "/usr/lib/python3/dist-packages/matplotlib/axis.py", line 912, in iter_ticks
majorLocs = self.major.locator()
File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 1794, in __call__
return self.tick_values(vmin, vmax)
File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 1802, in tick_values
locs = self._raw_ticks(vmin, vmax)
File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 1761, in _raw_ticks
istep = np.nonzero(steps >= raw_step)[0][0]
IndexError: invalid index to scalar variable.
It appears that there are only two lines involved. They are from the file /auto/07p/python/graphics/grapher_mpl.py.
The two methods involved are:
def redraw(self):
# recalculate label positions
self.grapher.plotlabels()
FigureCanvasTkAgg.draw(self)
And
def draw(self):
ax = self.grapher.ax
d = {}
if ax is self.grapher.ax3d:
[d["minx"], d["maxx"]] = ax.get_xlim3d()
[d["miny"], d["maxy"]] = ax.get_ylim3d()
[d["minz"], d["maxz"]] = ax.get_zlim3d()
d["azimuth"] = ax.azim
d["elevation"] = ax.elev
d["cur_lims"] = Axes.get_xlim(ax), Axes.get_ylim(ax)
else:
[d["minx"], d["maxx"]] = ax.get_xlim()
[d["miny"], d["maxy"]] = ax.get_ylim()
for k in list(d):
# don't adjust any unchanged settings
if k == "cur_lims":
if map(list, d[k]) == map(list, self.grapher._cur_lims):
del d[k]
elif d[k] == self.grapher.cget(k):
del d[k]
if d != {}:
if "cur_lims" in d:
del d["cur_lims"]
if d != {}:
self.grapher._configNoDraw(**d)
self.redraw()
return
FigureCanvasTkAgg.draw(self)
I would appreciate if anyone can assist me with the error, without changing the matlibplot code but only the auto code. I have read through the code but did not find anything suspicious.
I ran into this error using a given equation and auto file. But if you use matplotlib 2.0 and auto07p to plot most graphs in general, you are very likely to get this error if you zoom on the graph.
I used the files as the following:
https://1drv.ms/f/s!ArJqyyCr1FQOhkITst8JdVK_mIFV
Put them in auto folder.
Run auto.
and type:
auto("couple2.auto")
Thanks.

Plotting dates in matplotlib, one plot works the other doesn't

I am trying to plot some data with corresponding timestamps in python with matplotlib. The 'dates' are actually datetime.time objects (so no corresponding dates and I don't care about the dates) which look like this:
In[6]: dates[1]
Out[6]: datetime.time(12, 3, 1)
I have created a simple code which shows what I would like to do (and am doing with the actual data but isn't working for some reason):
Working Code
import matplotlib.pyplot as plt
import matplotlib.dates as pltdt
import datetime as dt
dates = [dt.time(12,3,i) for i in range(6)]
time_to_datetime = []
for i in dates:
time_to_datetime.append(dt.datetime.combine(dt.date.min, i))
dates_as_num = pltdt.date2num(time_to_datetime)
values = range(len(dates))
plt.plot_date(dates_as_num, values)
plt.show()
print ('Done!')
Which produces the following plot:
However, when I do this EXACT process with my data (of course instead of 6 points I have ~300,000 and there is some extra processing happening) I get the following error:
Traceback (most recent call last):
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 197, in __draw_idle_agg
FigureCanvasAgg.draw(self)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\figure.py", line 1143, in draw
renderer, self, dsu, self.suppressComposite)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axes\_base.py", line 2409, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 1136, in draw
ticks_to_draw = self._update_ticks(renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 969, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 969, in <listcomp>
tick_tups = [t for t in self.iter_ticks()]
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 912, in iter_ticks
majorLocs = self.major.locator()
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 983, in __call__
self.refresh()
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 1003, in refresh
dmin, dmax = self.viewlim_to_dt()
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 760, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 401, in num2date
return _from_ordinalf(x, tz)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 254, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: ordinal must be >= 1
Traceback (most recent call last):
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 197, in __draw_idle_agg
FigureCanvasAgg.draw(self)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\figure.py", line 1143, in draw
renderer, self, dsu, self.suppressComposite)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axes\_base.py", line 2409, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 1136, in draw
ticks_to_draw = self._update_ticks(renderer)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 969, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 969, in <listcomp>
tick_tups = [t for t in self.iter_ticks()]
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\axis.py", line 912, in iter_ticks
majorLocs = self.major.locator()
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 983, in __call__
self.refresh()
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 1003, in refresh
dmin, dmax = self.viewlim_to_dt()
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 760, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 401, in num2date
return _from_ordinalf(x, tz)
File "C:\Users\Will Evonosky\AppData\Local\Enthought\Canopy\edm\envs\User\lib\site-packages\matplotlib\dates.py", line 254, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: ordinal must be >= 1
%run "c:\users\willev~1\appdata\local\temp\tmpjkubsr.py"
I have tried everything I can to get this thing to work with no success. I tried even converting the times to strings and just manually setting the tick labels for the x-axis but ran into a problem where what showed up on the x-axis wasn't representing the actual dates accurately (where there should have been 200 minutes in minute intervals displayed, there was a total of 3 minutes displayed even though the y values spanned the whole 200 point range). Thanks for any help!
My trimmed code is below (sorry it is messy):
import matplotlib.pyplot as plt
import matplotlib.dates as pltdt
import numpy as np
import datetime as dt
import math
def plot_two_orbit(times, values):
fig2 = plt.figure(figsize = (14,8))
ax2=plt.subplot(111)
ax2.plot_date(times, values, linewidth=4)
ax2.set_xticklabels([i.strftime('%H:%M') for i in two_orbit_times])
ax2.yaxis.set_ticks_position("left")
ax2.xaxis.set_ticks_position("bottom")
ax2.spines['top'].set_color('None')
ax2.spines['right'].set_color('None')
ax2.spines['bottom'].set_color('black')
ax2.spines['left'].set_color('black')
ax2.tick_params(axis='x', colors='black', labelsize=20, pad=10)
ax2.tick_params(axis='y', colors='black', labelsize=20, pad=10)
ax2.yaxis.label.set_color('black')
ax2.xaxis.label.set_color('black')
ax2.set_ylabel(r'Ion Temp (K)', size=23)
ax2.set_xlabel(r'Local Time', size=23)
plt.show()
return None
#model parameters
modalt = np.arange(90, 1005, 5) #90km to 1000km in 5km increiments,
modlat = np.arange(-90, 92, 2) #latitude from 0 to 355 in 5 degree incriments
modlon = np.arange(0,356, 4) #longitude from -87.5 to 87.5 in 5 degree incriments
modtime = np.arange(.25,24.25,.25) # time in 15 minute incriments
#making the modtime array into a python datetime.time object
times = []
for i in modtime:
strip = [math.modf(i)[1],math.modf(i)[0]*60 ]
if strip[0]==24:
times.append(dt.time(0, int(strip[1]),0))
else:
times.append(dt.time(int(strip[0]), int(strip[1]),0))
#loading in the Model data
mdatas =np.load('C:/Users/Will Evonosky/Dropbox/SOARS/SOARS 2017/Data/GIP_Feb5_ti.npy')
#Function to find the index of the neasrest array point to a given value
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx
#load in the ephemeris data retrieved from STK
ephem = np.genfromtxt('C:/Users/Will Evonosky/Dropbox/SOARS/SOARS 2017/Data/STK Data/Location for count and science/Times_Loc_Fix_7mon_500km.csv', skip_header=1, dtype=None, delimiter=',')
#Pulling out the indivdual parameters from the STK data
sattime = [dt.datetime.strptime(i[1].decode('ascii'), '%H:%M').time() for i in ephem]
satlat = np.round([i[2] for i in ephem], decimals=2)
satlon = np.round([i[3] for i in ephem], decimals=2)
satalt = np.round([i[4] for i in ephem], decimals=2)
#making the modeled satellite longitude match GIP (-180 to 180) to (0 to 360)
satloncor = []
for i in satlon:
if i<0:
satloncor.append(round(i+360,2))
else:
satloncor.append(round(i,2))
#Converting UT times for satellite data into local solar time
localtimes = []
for (i,j) in zip(sattime, satloncor):
td = dt.datetime.combine(dt.datetime.min, i) - dt.datetime.min
seconds = td // dt.timedelta(seconds=1)
local = (seconds + (j/(360/86400)))/3600
if local>24:
local-=24
strip = [math.modf(local)[1],math.modf(local)[0]*60 ]
if strip[0]==24:
localtimes.append(dt.time(0, int(strip[1]),0))
else:
localtimes.append(dt.time(int(strip[0]), int(strip[1]),0))
#Creating empty arrays to hold the resulting values
grid_night_hour = np.zeros((24,len(modlat),len(modlon)))
two_orbit_line = []
two_orbit_times=[]
#Count determines how many orbits to sample. 1 orbit is ~ 90 data points
count = 200
night_hours = [20,21,22,23,0,1,2,3,4,5]
#plucking out the model data which most closely match the lat, lon, time, and alt of STK sat data
for (i,j,k,l,m) in zip(satlat, satloncor, sattime, satalt, localtimes):
mlat = find_nearest(modlat, i)
mlon = find_nearest(modlon, j)
malt = find_nearest(modalt, l)
mtime = times.index(min(times, key=lambda d: abs(dt.datetime.combine(dt.date.min,d) - dt.datetime.combine(dt.date.min,k))))
if m.hour in night_hours:
grid_night_hour[m.hour, mlat, mlon] = mdatas[malt, mlat, mlon, mtime]
if count > 0:
two_orbit_line.append(mdatas[malt, mlat, mlon, mtime])
two_orbit_times.append(pltdt.date2num(dt.datetime.combine(dt.date.min,m)))
count-=1
#masking zero values so they wont plot
grid_night_hour[grid_night_hour == 0.0] = np.nan
grid_night_hour = grid_night_hour - np.nanmean(grid_night_hour)
#Plotting the data
plot_two_orbit(two_orbit_times, two_orbit_line)
print ('Done!')
I figured it out. Y.Luo was on the right track even though their formulation was incorrect. I think that the minimum year supported by pythons datetime library is too low for the dates recognized by matploltib and the same goes for the max years. I manually inserted a date (changed code below) and the plot suddenly worked. Now I am running into another issue but that will have to be for another question.
if count > 0:
two_orbit_line.append(mdatas[malt, mlat, mlon, mtime])
two_orbit_times.append(pltdt.date2num(dt.datetime.combine(dt.date(2019,1,1),m)))
count-=1

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

Categories

Resources