Animating moving sphere
I want to create an animation of a moving sphere in matplotlib. This is what I've wrote so far
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import cm
from matplotlib import animation
import pandas as pd
fig = plt.figure(facecolor='black')
ax = plt.axes(projection = "3d")
u = np.linspace(0, 2*np.pi, 100)
v = np.linspace(0, np.pi, 100)
r = 4
ax.set_xlim(0, 60)
ax.set_ylim(0, 60)
ax.set_zlim(0, 60)
x0 = r * np.outer(np.cos(u), np.sin(v)) + 10
y0 = r * np.outer(np.sin(u), np.sin(v)) + 10
z0 = r * np.outer(np.ones(np.size(u)), np.cos(v)) + 50
def init():
ax.plot_surface(x0,y0,z0)
return fig,
def animate(i):
ax.plot_surface(x0 + 1, y0 + 1, z0 + 10)
return fig,
ani = animation. FuncAnimation(fig, animate, init_func = init, frames = 90, interval = 300)
plt.show()
Here, I have attempted to move the sphere by (1,1,1) in each new iteration, but it fails to do so.
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Rotate and translate image from center to all directions one by one in ios swift
I am trying to make a demo of animation for learning but i am having issue regarding coordinate system of apple and how does it work when trying for animations. The issue is i have 6 static images stacked upon each other as pile of playing cards and have 6 empty views in all directions which is of same height and width as the pile cards height width. Now how do i rotate and translate card 6 to bottomleft then card 5 to topleft then card 4 to top center card3 to topright then card 2 to bottom right and card1 to bottom center i.e more like a playing card distribution animation
-
Javascript request animation frame irregular translation
SO community! I'm trying to make an object move at the same phase as scroll using CSS transform. The problem is that I see the animation is not smooth. Instead, is like the box is flickering and 'jumping' all the time, and I can't figure out the cause.
How can I achieve these kinds of transformations in a smooth way?
I will leave my code below, as well as a codepen link.
Thanks beforehand for your help!
const container = document.querySelector('.container'); const box = document.querySelector('.box'); function animate() { transformBox(); requestAnimationFrame(animate); } function transformBox() { const scrollY = window.scrollY; box.style.transform = `translate3d(0, ${scrollY}px, 0)`; } animate();
* { margin: 0; padding: 0; box-sizing: border-box; } html, body { overscroll-behavior: none; } .container { position: relative; height: 400vh; background-color: #333; } .box { position: absolute; top: calc(50vh - 25px); left: calc(50% - 25px); width: 50px; height: 50px; background-color: white; border-radius: 8px; }
<div class="container"> <div class="box"></div> </div>
-
How to make xlim and ylim dynamically change?
I'm reading sensor data connected to Arduino, in the image below I want to make x_lim and y_lim change dynamically while reading data. for example, i need to add DateTime in x_lim and y_lim sensor values
class CustomFigCanvas(FigureCanvas, TimedAnimation): def __init__(self): self.addedData = [] print(matplotlib.__version__) self.xlim = 200 # The window self.fig = Figure(figsize=(5,5), dpi=100) self.ax1 = self.fig.add_subplot(111) # self.ax1 settings self.ax1.set_xlabel('time') self.ax1.set_ylabel('raw data') self.line1 = Line2D([], [], color='blue') self.line1_tail = Line2D([], [], color='red', linewidth=2) self.line1_head = Line2D([], [], color='red', marker='o', markeredgecolor='r') self.ax1.add_line(self.line1) self.ax1.add_line(self.line1_tail) self.ax1.add_line(self.line1_head) self.ax1.set_xlim(0, self.xlim - 1) # Here Should be sensor values change automatically self.ax1.set_ylim(100, 400) # Here Should be time in seconds change automatically FigureCanvas.__init__(self, self.fig) TimedAnimation.__init__(self, self.fig, interval = 50, blit = True) return
def addData(self, value): self.addedData.append(value) return def dataSendLoop(addData_callbackFunc): mySrc = Communicate() mySrc.data_signal.connect(addData_callbackFunc) n = np.linspace(0, 499, 500) y = [] i = 0 while(True): line = board.analogRead(0) # Here i reading sensor data y.append(line) mySrc.data_signal.emit(y[i]) # <- Here you emit a signal! i += 1
-
Animating grid with FuncAnimation converges almost immediately to a single color
I am modeling phase separation in python. When I use matplotlib's FuncAnimation, the grid converges to the same color almost immediately. When I use a simple loop and redraw on each iteration, the simulation evolves as I would expect. I would prefer to use FuncAnimation if possible.
In this code, the grid is all purple within a second or so
fig, ax = plt.subplots() im1 = ax.imshow(self.grid) animation.FuncAnimation(fig, self.my_update_func 100000 init_func = self.my_init_func, repeat = False, blit=True, fargs=(im1,), interval = 100) plt.show() my_update_func(self, i, img) self.update_grid() img.set_data(self.grid) return img,
Whereas in this code the animation evolves as a phase separation simulation would be expected to do:
for i in range(1,100000): self.upgrade_grid() if i % 1000 == 0: plt.imshow(self.grid, animated=True, cmap='plasma') plt.draw() plt.pause(0.001)
Can someone please tell me why the FuncAnimation method is not working?
Thank you