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
Related
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'
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.
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} )$')
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.
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