plot RA/Dec polygons with astropy wcs aplpy FITSFigure - python

I've got some polygons in RA/Dec spherical coordinates, and I'm trying to plot them with aplpy and an astropy world coordinate system (WCS) object, but my script crashes.
I can reproduce the problem with this standalone script:
#!/usr/bin/env python
import astropy
import aplpy, numpy
from numpy import array
import matplotlib.pyplot as plt
from matplotlib import cm, colors
from astropy.wcs import WCS
cent_ra = 1 # plot center, ra, deg
cent_dec = 88 # plot center, dec, deg
rad = 7 # plot radius, deg
rad_pix = 300 # plot radius, pixels
# two polygons to plot, in ra-dec space
polygons_radec = [ array([[ 1.0, 88.0],[ 2.0, 88.0],[ 2.0, 89.0],[ 1.0, 88.0]]),
array([[ 1.0, 88.0],[ 2.0, 88.0],[ 2.0, 87.0],[ 1.0, 88.0]]) ]
zvalues = [5,2]
# setup our radec-pixel coordinate transformation
w = WCS( naxis=2 )
w.naxis1 = 2 * rad_pix
w.naxis2 = 2 * rad_pix
w.wcs.crpix = [rad_pix, rad_pix] # reference pixel
w.wcs.crval = [ cent_ra, cent_dec ] # reference pixel's ra/dec coordinate?
w.wcs.cdelt = array([ rad/rad_pix, rad/rad_pix ]) # pixel delta in ra/dec space?
w.wcs.ctype = ['RA--TAN','DEC-TAN']
# convert the ra-dec polygon coordinates to pixel coordinates
polygons = []
for p in polygons_radec :
polygon = []
for c in p :
polygon += [ w.wcs_world2pix( c[0], c[1], 1 ) ]
polygons += [ array( polygon ) ]
print('polygons:')
print(polygons)
print()
# plot our polygons with colors
cmap1 = cm.YlOrBr
norm1 = colors.Normalize( numpy.min(zvalues), numpy.max(zvalues) )
fig = aplpy.FITSFigure( w )
for p, c in zip( polygons, zvalues ) :
fig.show_polygons( [p], facecolor=cmap1(norm1(c)), edgecolor='none', alpha=0.3 )
plt.savefig( 'plot.png' , dpi=300 )
When I try to run this, I get a rather large traceback/exception:
Traceback (most recent call last):
File "./test.py", line 46, in <module>
plt.savefig( 'plot.png' , dpi=300 )
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 696, in savefig
res = fig.savefig(*args, **kwargs)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/figure.py", line 1563, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5agg.py", line 203, in print_figure
FigureCanvasAgg.print_figure(self, *args, **kwargs)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/backend_bases.py", line 2232, in print_figure
**kwargs)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/backends/backend_agg.py", line 527, in print_png
FigureCanvasAgg.draw(self)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/backends/backend_agg.py", line 474, in draw
self.figure.draw(self.renderer)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/figure.py", line 1159, in draw
func(*args)
File "/.../miniconda3/lib/python3.5/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py", line 295, in draw
self._get_base_axes_attr("draw")(self, renderer)
File "/.../miniconda3/lib/python3.5/site-packages/mpl_toolkits/axisartist/axislines.py", line 772, in draw
super(Axes, self).draw(renderer, inframe)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/axes/_base.py", line 2319, in draw
a.draw(renderer)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/axis.py", line 1108, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/axis.py", line 951, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/axis.py", line 951, in <listcomp>
tick_tups = [t for t in self.iter_ticks()]
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/axis.py", line 898, in iter_ticks
for i, val in enumerate(majorLocs)]
File "/.../miniconda3/lib/python3.5/site-packages/matplotlib/axis.py", line 898, in <listcomp>
for i, val in enumerate(majorLocs)]
File "/.../miniconda3/lib/python3.5/site-packages/aplpy/labels.py", line 421, in __call__
label = self.axis.apl_tick_spacing * self.axis.apl_tick_positions_world[ipos]
File "/.../miniconda3/lib/python3.5/site-packages/aplpy/angle_util.py", line 242, in __mul__
s = Angle(sexagesimal=(d, m, s), latitude=self.latitude)
File "/.../miniconda3/lib/python3.5/site-packages/aplpy/angle_util.py", line 52, in __init__
self._simplify()
File "/.../miniconda3/lib/python3.5/site-packages/aplpy/angle_util.py", line 88, in _simplify
degrees")
Exception: latitude should be between -90 and 90
The plot overlaps one of the spherical coordinate system's poles (Declination=90 deg), so I'm wondering if that's causing a problem/revealing a bug, or if its because I've set up my WCS incorrectly.
How can I get the polygons to show up?

Related

plotting dynamic time evolution in matplotlib with x axis as numpy linspace and y axis as differential equation(odeint)

I am trying to create a program that takes a model of differential equations as input, and shows its evolution with time in an animated/slider graph. For now, im just using the SIR model of infectious disease spread but I plan to make it so that it can user input differential equations upto models with 5 equations. I seem to have no problem in making a normal graph using plt.plot, but when i try to make the graph dynamic/interactive, it gives me similar errors:
'''
enter total population: 10000
enter number of infected people: 20
enter number of recovered people: 0
Traceback (most recent call last):
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\cbook\__init__.py", line 287, in process
func(*args, **kwargs)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\widgets.py", line 585, in <lambda>
return self._observers.connect('changed', lambda val: func(val))
File "e:\Python\bio3636\exam2.py", line 45, in update
ax.plot(t1, sir1)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\axes\_axes.py", line 1632, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\axes\_base.py", line 312, in __call__
yield from self._plot_args(this, kwargs)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\axes\_base.py", line 498, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (1,) and (1000, 3)
this ^ is for when i use a slider object
enter total population: 10000
enter number of infected people: 20
enter number of recovered people: 0
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 814, in callit
func(*args)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\backends\_backend_tk.py", line 252, in idle_draw
self.draw()
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\backends\backend_tkagg.py", line 9, in draw
super().draw()
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\backends\backend_agg.py", line 436, in draw
self.figure.draw(self.renderer)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\artist.py", line 73, in draw_wrapper
result = draw(artist, renderer, *args, **kwargs)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\figure.py", line 2837, in draw
mimage._draw_list_compositing_images(
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\axes\_base.py", line 3091, in draw
mimage._draw_list_compositing_images(
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\lines.py", line 732, in draw
self.recache()
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\matplotlib\lines.py", line 661, in recache
self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float)
File "<__array_function__ internals>", line 180, in broadcast_arrays
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\numpy\lib\stride_tricks.py", line 540, in broadcast_arrays
shape = _broadcast_shape(*args)
File "C:\Users\Avi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\numpy\lib\stride_tricks.py", line 422, in _broadcast_shape
b = np.broadcast(*args[:32])
ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (1000,) and arg 1 with shape (3000,).
this is for animated graph.
here's my code:
#Plotting a dynamic graph to observe time evolution of a diffn eq. Furthermore,
# plot the points in an excel file for easy access data.
from cProfile import label
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
import matplotlib.animation as animation
from matplotlib.widgets import Slider
#t1 = float(input('enter starting time: '))
#t2 = float(input('enter ending time: '))
#d = float(input('enter divisions: '))
t = np.linspace(0, 100, 1000)
ttest = [a for a in range(0,1000)]
et =[]
for i in ttest:
et.append(i/10)
def model(z,t,k1,k2):
s,i,r = z
dsdt = -k1*s*i
didt = (k1*s*i) - k2*i
drdt = k2*i
return [dsdt, didt, drdt]
p = int(input('enter total population: '))
i = int(input('enter number of infected people: '))
r = int(input('enter number of recovered people: '))
z0 = [p-i, i, r]
k1 = 0.5
k2 = 1/3
sir = odeint(model, z0, t, args = (k1,k2))
fig = plt.figure()
ax = fig.add_subplot(111)
#fig.subplots_adjust(bottom = 0.2, top = 0.75)
#s = fig.add_axes([0.3, 0.92, 0.4, 0.05])
#s.spines['top'].set_visible(True)
#s.spines['right'].set_visible(True)
#sl = Slider(ax = s, label = 'time', valmin = 0, valmax = 100, valinit = 100 )
f_d = ax.plot([], [])[0]
#def update(val):
# t1 = sl.val
# sir1 = sir
#ax.plot(t1, sir1)
#fig.canvas.draw_idle()
#sl.on_changed(update)
def ani(i):
x = t
y = sir
f_d.set_data(x,y)
a = animation.FuncAnimation(fig = fig, func = ani, frames = range(len(t)), interval = 500)
plt.show()
any help would be appreciated, thanks.

Using matplotlib scatter markers in text of legend together with Latex

I have a plot with an inset. The latter has a legend, in whose text I would like to use matplotlib scatter markers. I also want to be able to use LaTeX at the same time for all the labels and legends. The reason I am mentioning this is because I had a look at this thread and the solutions there don't work for me. I will explain why bellow.
Here is an example code (sorry for the functions I am plotting, couldn't think of anything)
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.inset_locator import (inset_axes, InsetPosition, mark_inset)
from matplotlib import rc
rc('text', usetex=True)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
fig, ax1 = plt.subplots()
ax1.scatter(x, np.cos(x), color = 'blue', marker = "D", s=47.5, label = r'$\cos$')
ax1.scatter(y, np.sin(y), color = 'cyan', marker = "*", alpha = 0.85, label = r'$\sin$')
ax1box = ax1.get_position()
x_value = -0.13
y_value = 0.675
legend=ax1.legend(loc = (ax1box.x0 + x_value, ax1box.y0 + y_value), handletextpad=0.1, prop={'size':8})
frame = legend.get_frame()
frame.set_alpha(0)
frame.set_linewidth(0)
ax2 = plt.axes([0.5,0.5,0.5,0.5])
ip = InsetPosition(ax1, [0.55,0,0.45,0.40])
ax2.set_axes_locator(ip)
ax2.scatter(x, np.tan(x), color = 'gray', marker = "v", s=15, label = r'Insert blue square marker here')
ax2.scatter(y, np.log(y)+1, color = 'brown', marker = "4", s=15, label = r'Insert cyan star marker here')
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
ax2.yaxis.tick_right()
legend2=ax2.legend(loc = 'lower right', handletextpad=0.1, prop={'size':7})
frame2 = legend2.get_frame()
frame2.set_alpha(0)
frame2.set_linewidth(0)
plt.show()
If I am to go with the advice in here about LaTeX and try with
ax2.scatter(x, np.tan(x), color = 'gray', marker = "v", s=15, label = r'$\square$')
the plot shows with no legend in the inset.
If, instead, I decide to implement the unicode solution
ax2.scatter(x, np.tan(x), color = 'gray', marker = "v", s=15, label = '●')
I get the following error
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/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 280, in resize
self.show()
File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/figure.py", line 1144, in draw
renderer, self, dsu, self.suppressComposite)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_base.py", line 2426, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/legend.py", line 471, in draw
bbox = self._legend_box.get_window_extent(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 269, in get_window_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 262, in get_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 262, in get_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 262, in get_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 835, in get_extent
bbox, info, d = self._text._get_layout(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/text.py", line 362, in _get_layout
ismath=ismath)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_agg.py", line 230, in get_text_width_height_descent
renderer=self)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/texmanager.py", line 676, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/texmanager.py", line 399, in make_dvi
texfile = self.make_tex(tex, fontsize)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/texmanager.py", line 314, in make_tex
fh.write(s.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode character '\u25cf' in position 226: ordinal not in range(128)
Which seems to come from the fact that I am using LaTeX, as If I comment out
# from matplotlib import rc
# rc('text', usetex=True)
Then I get everything working, but without LaTeX. (Well the circle I get is black, I haven't looked into whether it is possible to change its colour yet). I do want LaTeX, though, so this is not good for me.
As The Great, Big List of LaTeX Symbols tells us, \square is an AMS symbol. So, in order to use it you have to put \usepackage{amssymb} in your preamble, which can be done with
rc('text', usetex=True)
rc('text.latex', preamble=r'\usepackage{amssymb}')

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

ValueError in matplotlib when using \: LaTeX horizontal spacing

See MWE below:
import matplotlib.pyplot as plt
import matplotlib.offsetbox as offsetbox
fig = plt.figure()
ax = fig.add_subplot(111)
text1 = r'$a\,=\,{}\pm{}$'.format(0.01, 0.002) # Works.
text2 = r'$a\;=\,{}\pm{}$'.format(0.01, 0.002) # Works.
text3 = r'$a\:=\,{}\pm{}$'.format(0.01, 0.002) # Does not work.
text = text3
ob = offsetbox.AnchoredText(text, pad=1, loc=6, prop=dict(size=13))
ob.patch.set(alpha=0.85)
ax.add_artist(ob)
plt.show()
While text1 and text2 which use \, and \; spacing will work without issues, text3 which uses \: (ie: the horizontal spacing located between the previous two) fails with a ValueError:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 42, in on_draw_event
self._render_figure(w, h)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 32, in _render_figure
backend_agg.FigureCanvasAgg.draw(self)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 469, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1085, in draw
func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2110, in draw
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1107, in draw
bbox = self.get_window_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1063, in get_window_extent
w, h, xd, yd = self.get_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1014, in get_extent
w, h, xd, yd = self.get_child().get_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 782, in get_extent
bbox, info, d = self._text._get_layout(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/text.py", line 320, in _get_layout
ismath=ismath)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 228, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/mathtext.py", line 3005, in parse
box = self._parser.parse(s, font_output, fontsize, dpi)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/mathtext.py", line 2339, in parse
six.text_type(err)]))
ValueError:
a\:=\,0.01\pm0.002
^
Unknown symbol: \ (at char 1), (line:1, col:2)
Why is this LaTeX spacing not recognized?
Because matplotlib uses mathtext as default math renderer. Mathtext is a subset of regular TeX. You can use full LaTeX with:
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] #if needed
plt.plot([1,2,3])
plt.title(r"$a\:=\,{}\pm{}$".format(0.01, 0.002))
plt.show()

Categories

Resources