I'm trying to animate a piece of text in matplotlib, in order to make some educational videos. However, I'm having trouble with setting text in motion.
I've tried to use FuncAnimation (as I did for animating lines), and defining the anchor of that text as a pair of moving coordinates. Here's what I've tried:
def data_gen(): #Data generator. Gives me the anchor.
counter = 0
x0 = data_gen.x0
while counter < 1000:
counter+=1
x0-=0.09
yield x0,(1-counter*0.05)
data_gen.x0=1
def animate_text(data): #Here is where I try to tell my code to refresh
#only the coordinates of the text.
x0,y0 = data
text_sample = ax.text(x0,y0,'text here',transform=ax.transAxes,
fontsize=12, color='black',fontstyle='oblique',family='serif')
return text_sample
#animation part:
ani = animation.FuncAnimation(fig,animate_text,data_gen,blit=True,
interval=50,repeat = False)
plt.show()
However, I get this:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 387,
in process
proxy(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 227,
in __call__
return mtd(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1026, in
_start
self._init_draw()
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1750, in
_init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1777, in
_draw_frame
for a in self._drawn_artists:
TypeError: 'Text' object is not iterable
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 387,
in process
proxy(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\cbook\__init__.py", line 227,
in __call__
return mtd(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1308, in
_handle_resize
self._init_draw()
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1750, in
_init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 1777, in
_draw_frame
for a in self._drawn_artists:
TypeError: 'Text' object is not iterable
Does anybody know how can I solve that?
In FuncAnimation documentation you can read:
func must return an iterable of all artists that were modified or
created
"iterable" means that animate_text() has to return list or tuple with elements - even if you have only one element:
return (text_sample,)
Related
The following code
If I run the following code in pdb (i.e. with python -m pdb)
if __name__=='__main__':
import pandas as pd
df=pd.DataFrame([[0,1,2],[63,146, 135]])
df.plot.area()
it fails with a TypeError inside a numpy routine that's called by matplotlib:
> python -m pdb test_dtype.py
> /home/jhaiduce/financial/forecasting/test_dtype.py(1)<module>()
-> if __name__=='__main__':
(Pdb) r
QSocketNotifier: Can only be used with threads started with QThread
--Return--
> /home/jhaiduce/financial/forecasting/test_dtype.py(6)<module>()->None
-> df.plot.area()
(Pdb) c
Traceback (most recent call last):
File "/usr/lib64/python3.10/site-packages/numpy/core/getlimits.py", line 384, in __new__
dtype = numeric.dtype(dtype)
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib64/python3.10/pdb.py", line 1726, in main
pdb._runscript(mainpyfile)
File "/usr/lib64/python3.10/pdb.py", line 1586, in _runscript
self.run(statement)
File "/usr/lib64/python3.10/bdb.py", line 597, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "/home/jhaiduce/financial/forecasting/test_dtype.py", line 6, in <module>
df.plot.area()
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_core.py", line 1496, in area
return self(kind="area", x=x, y=y, **kwargs)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_core.py", line 972, in __call__
return plot_backend.plot(data, kind=kind, **kwargs)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py", line 71, in plot
plot_obj.generate()
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 294, in generate
self._post_plot_logic_common(ax, self.data)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 473, in _post_plot_logic_common
self._apply_axis_properties(ax.xaxis, rot=self.rot, fontsize=self.fontsize)
File "/usr/lib64/python3.10/site-packages/pandas/plotting/_matplotlib/core.py", line 561, in _apply_axis_properties
labels = axis.get_majorticklabels() + axis.get_minorticklabels()
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1201, in get_majorticklabels
ticks = self.get_major_ticks()
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1371, in get_major_ticks
numticks = len(self.get_majorticklocs())
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1277, in get_majorticklocs
return self.major.locator()
File "/usr/lib64/python3.10/site-packages/matplotlib/ticker.py", line 2113, in __call__
vmin, vmax = self.axis.get_view_interval()
File "/usr/lib64/python3.10/site-packages/matplotlib/axis.py", line 1987, in getter
return getattr(getattr(self.axes, lim_name), attr_name)
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 781, in viewLim
self._unstale_viewLim()
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 776, in _unstale_viewLim
self.autoscale_view(**{f"scale{name}": scale
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 2932, in autoscale_view
handle_single_axis(
File "/usr/lib64/python3.10/site-packages/matplotlib/axes/_base.py", line 2895, in handle_single_axis
x0, x1 = locator.nonsingular(x0, x1)
File "/usr/lib64/python3.10/site-packages/matplotlib/ticker.py", line 1654, in nonsingular
return mtransforms.nonsingular(v0, v1, expander=.05)
File "/usr/lib64/python3.10/site-packages/matplotlib/transforms.py", line 2880, in nonsingular
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
File "/usr/lib64/python3.10/site-packages/numpy/core/getlimits.py", line 387, in __new__
dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /usr/lib64/python3.10/site-packages/numpy/core/getlimits.py(387)__new__()
-> dtype = numeric.dtype(type(dtype))
(Pdb)
The error occurs only when run in the debugger; the program runs as normal when run outside the debugger.
Any idea what could be the cause of this?
So, I'm trying to animate some pixels moving around a static image using FuncAnimation. The static image itself is 256x256 and the objects moving around are essentially a brightly colored pixel. In the end i'd like for the animation to go indefinitely or until I stop it but thats besides the point. Right now I'd like to get things moving first.
The static image in question is this one (for this example anyways).
The code below is a simple class consisting of a location and color. When i spawn it or move it i make sure to record the previous pixel color so the object doesnt leave 'tracks' sort of speak.
class Prey:
def __init__(self, color = [255, 0, 255]) -> None:
self.color = color
self.x = None
self.y = None
def set_spawn(self, world):
self.x = random.randint(0, 256)
self.y = random.randint(0, 256)
while np.array_equal(world[self.x][self.y], [65, 105, 225]):
self.x = random.randint(0, 256)
self.y = random.randint(0, 256)
prev_pix = world[self.x, self.y]
return prev_pix
def move(self, world, x, y):
if not np.array_equal(world[x][y], [65, 105, 225]):
prev_pix = ((self.x, self.y), world[x][y])
self.x = x
self.y = y
return prev_pix
And below here I actually try to animate the damn thing.
def load_map(wname):
bgr_world = cv2.imread(wname)
rgb_world = cv2.cvtColor(bgr_world, cv2.COLOR_BGR2RGB)
return rgb_world
world = load_map('m3.png')
fig = plt.figure('lifesim')
im = plt.imshow(world, animated=True)
p1 = Prey()
def movement(*args):
x1, y1, prev_pix1 = p1.move(world, p1.x+1, p1.y) #i'm trying to get it to move down (when it actually works ill make sure it doesnt go OOB)
ppxy, pp = prev_pix1
ppx, ppy = ppxy
world[ppx][ppy] = pp
world[x1][y1] = p1.color
im.set_array(world)
return world,
def init_game(world):
x0, y0, prev_pix0 = p1.set_spawn(world) #The spawn is random, so i just overwrote it here so i can test
prev_pix0 = world[110, 100]
x0, y0 = (110, 100)
p1.x = 110
p1.y = 100
world[x0][y0] = p1.color
ani = animation.FuncAnimation(fig, movement, blit=True)
plt.show()
def main():
init_game(world)
if __name__ == "__main__":
main()
And when the code gets eventually executed, i get the following error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Python39\lib\site-packages\matplotlib\backends\_backend_tk.py", line 241, in resize
self.resize_event()
File "C:\Python39\lib\site-packages\matplotlib\backend_bases.py", line 1767, in resize_event
self.callbacks.process(s, event)
File "C:\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 229, in process
self.exception_handler(exc)
File "C:\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 81, in _exception_printer
raise exc
File "C:\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 224, in process
func(*args, **kwargs)
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 1275, in _on_resize
self._init_draw()
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 1719, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 1747, in _draw_frame
self._drawn_artists = sorted(self._drawn_artists,
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 1748, in <lambda>
key=lambda x: x.get_zorder())
AttributeError: 'numpy.ndarray' object has no attribute 'get_zorder'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Python39\lib\tkinter\__init__.py", line 814, in callit
func(*args)
File "C:\Python39\lib\site-packages\matplotlib\backends\_backend_tk.py", line 253, in idle_draw
self.draw()
File "C:\Python39\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 9, in draw
super(FigureCanvasTkAgg, self).draw()
File "C:\Python39\lib\site-packages\matplotlib\backends\backend_agg.py", line 407, in draw
self.figure.draw(self.renderer)
File "C:\Python39\lib\site-packages\matplotlib\artist.py", line 41, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Python39\lib\site-packages\matplotlib\figure.py", line 1870, in draw
self.canvas.draw_event(renderer)
File "C:\Python39\lib\site-packages\matplotlib\backend_bases.py", line 1759, in draw_event
self.callbacks.process(s, event)
File "C:\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 229, in process
self.exception_handler(exc)
File "C:\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 81, in _exception_printer
raise exc
File "C:\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 224, in process
func(*args, **kwargs)
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 975, in _start
self._init_draw()
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 1719, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 1747, in _draw_frame
self._drawn_artists = sorted(self._drawn_artists,
File "C:\Python39\lib\site-packages\matplotlib\animation.py", line 1748, in <lambda>
key=lambda x: x.get_zorder())
AttributeError: 'numpy.ndarray' object has no attribute 'get_zorder'
I'm not sure what I'm doing wrong here since I'm completely new to matplotlibs animation modules... The mistake is probably blisteringly obvious but I just can't see it.
I'm trying to set a value on this dropdown but am having trouble doing so. I've tried using the .select(index) method and that doesn't do anything. I've tried doing .typekeys("{DOWN 2}"), which usually works, but I think because another dropdown is selected before hand or something, it's not working. My usual workaround for this is to do .expand() and then .type_keys("{DOWN 2}"), and then .type_keys("{ENTER}"). I can't do this last workaround, because the control is not being wrapped as a combobox, as it should be.
Is there a way I can change it's wrapper? I tried:
from pywinauto import controls
test = controls.uia_controls.ComboBoxWrapper(formJobStock.child_window(auto_id='cboStockSize'))
test.expand()
but I get:
Traceback (most recent call last):
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 250, in __resolve_control
ctrl = wait_until_passes(
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uia_controls.py", line 143, in expand
if self.is_expanded():
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 561, in is_expanded
state = self.get_expand_state()
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uia_controls.py", line 188, in get_expand_state
return super(ComboBoxWrapper, self).get_expand_state()
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 556, in get_expand_state
return self.iface_expand_collapse.CurrentExpandCollapseState
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 132, in __get__
value = self.fget(obj)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 210, in iface_expand_collapse
return uia_defs.get_elem_interface(elem, "ExpandCollapse")
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\uia_defines.py", line 233, in get_elem_interface
cur_ptrn = element_info.GetCurrentPattern(ptrn_id)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 379, in __getattribute__
ctrls = self.__resolve_control(self.criteria)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 261, in __resolve_control
raise e.original_exception
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 222, in __get_ctrl
ctrl = self.backend.generic_wrapper_class(findwindows.find_element(**ctrl_criteria))
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findwindows.py", line 84, in find_element
elements = find_elements(**kwargs)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findwindows.py", line 305, in find_elements
elements = findbestmatch.find_best_control_matches(best_match, wrapped_elems)
File "C:\Users\mflanagan\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findbestmatch.py", line 536, in find_best_control_matches
raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'element' in 'dict_keys(['Edit', 'Edit0', 'Edit1', 'Edit2', 'Open', 'Button', 'OpenButton'])'
where formJobStock is a window specification:
formJobStock = window.child_window(auto_id='frmJobStock')
and I know it's found because I've done formJobStock.wrapper_object() and it comes up correctly.
It looks like I'm not passing in the element parameter correctly to the controls.controls_uia.ComboBoxWrapper class init call...any idea on how to do that correctly?
"""
I am trying to plot a graph from data retrieved from a CSV file. The code is as below
"""
path = '/Users/pradeepallath/Documents/000_Edureka_Training/001_PredictiveAnalysis/Weather_WWII'
import pandas as pd
dataset = pd.read_csv(path+'/Weather.csv',low_memory=False,nrows=1000)
dataset.plot(x='MinTemp',y='MaxTemp',style=0)
plt.plot()
"""
I am Getting this error. Please note I am new to Python
Traceback (most recent call last):
File "/Users/pradeepallath/Documents/Pycharm/Big_Mart_Sale/Mean_Sale.py", line 13, in <module>
dataset.plot(x='MinTemp',y='MaxTemp',style=0)
File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py", line 794, in __call__
return plot_backend.plot(data, kind=kind, **kwargs)
File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/__init__.py", line 62, in plot
plot_obj.generate()
File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/core.py", line 281, in generate
self._make_plot()
File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/core.py", line 1063, in _make_plot
style, kwds = self._apply_style_colors(colors, kwds, i, label)
File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/core.py", line 723, in _apply_style_colors
nocolor_style = style is None or re.match("[a-z]+", style) is None
File "/Users/pradeepallath/anaconda3/lib/python3.7/re.py", line 173, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object
Thanks for the assistance
"""
It's taking issue with style=0.
Pandas supports matplotlib line styles.
Here is a good stackoverflow question on how you can see valid options, but essentially the integer zero is not a valid line style.
I have lost ability to plot against datetime object after upgrading of matplotlib.
Error is following:
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/pyplot.py", line 2813, in plot
is not None else {}), **kwargs)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/__init__.py", line 1810, in inner
return func(ax, *args, **kwargs)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 1611, in plot
for line in self._get_lines(*args, **kwargs):
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 393, in _grab_next_args
yield from self._plot_args(this, kwargs)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 370, in _plot_args
x, y = self._xy_from_xy(x, y)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 204, in _xy_from_xy
bx = self.axes.xaxis.update_units(x)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axis.py", line 1475, in update_units
self.set_units(default)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axis.py", line 1548, in set_units
self._update_axisinfo()
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axis.py", line 1490, in _update_axisinfo
info = self.converter.axisinfo(self.units, self)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_converter.py", line 353, in axisinfo
majfmt = PandasAutoDateFormatter(majloc, tz=tz)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_converter.py", line 367, in __init__
self._tz._utcoffset = self._tz.utcoffset(None)
AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'
Is it possible to upgrade without loosing capabilities in Python?
I think a viable workaround is indicated by this question. Basically, if you convert the pandas timestamps to str and then back to datetime, it magically works.