I have to create a pendulum simulation on plot. I have to read data from file, then only thing I have to solve is X and Y cords, what I did. It is specified that I am supposed to use "roll"/"pitch"/"yaw" columns and with one of them make a simulation.
There is the file: https://pastebin.com/D2Tt3tBj
Here is my code:
import pandas as pd
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from mpl_toolkits.mplot3d import Axes3D
from tkinter import ttk
from tkinter import scrolledtext
import numpy as np
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
pd.set_option('display.max_rows', None) # wyswietla caly plik
def odrzuc_n(df_full, n):
df_full = df_full.iloc[n:]
return df_full
def wczytaj_dane():
data = pd.read_csv("outputPendulum02.log", delim_whitespace=True)
data.columns = ["roll", "pitch", "yaw", "a_x", "a_y", "a_z", "m_x", "m_y", "m_z", "omega_x", "omega_y", "omega_z"]
data = data.drop(columns=["a_x", "a_y", "a_z", "m_x", "m_y", "m_z", "omega_x", "omega_y", "omega_z"])
data.index = [x for x in range(1, len(data.values) + 1)]
data.index.name = 'id'
df = pd.DataFrame(data)
seconds = []
x_cord = []
y_cord = []
which_angle = 'pitch'
for (index_label, row_series) in df.iterrows():
second = index_label * 0.04
seconds.append(second)
x = 50 * np.sin(row_series[which_angle])
y = 50 - 50 * np.cos(row_series[which_angle])
x_cord.append(x)
y_cord.append(y)
df['seconds'] = seconds
df['x_cord'] = x_cord
df['y_cord'] = y_cord
# print(df)
return df
df_full = wczytaj_dane()
how_many_to_delete = 500
df_full = odrzuc_n(df_full, how_many_to_delete)
data_cut = df_full
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')
def init(): # only required for blitting to give a clean slate.
ax.set_xlim(df_full['x_cord'].min()-5, df_full['x_cord'].max()+5)
ax.set_ylim(df_full['y_cord'].min()-5, df_full['y_cord'].max()+5)
return ln,
def update(frame):
xdata = (df_full.iloc[frame, 4])
ydata = (df_full.iloc[frame, 5])
ln.set_data(xdata, ydata)
if frame > 1225:
return 0
return ln,
ani = FuncAnimation(fig, update, frames=range(how_many_to_delete, 1225),
init_func=init, blit=True)
plt.show()
It's little messy... "odrzuc_n" function is function that drops N rows from dataframe. "Wczytaj_dane" is reading data from file. Columns of file are described in the code.
And finally my question. What's wrong with it? It shows an error at the end of animation. I don't really know is the X and Y determined properly. I have to make it in GUI that's why I have tkinter impoerted etc. But this part of code only generates plot.
Related
I want to draw a graphic with using datas in datetime format as xaxis, but the process lasts very, very, extremly long, over 30 mins there is still no graphic. But once I apply datas in another column, the graphic will occur very soon. All the datas' formats are 'list'.
I'm confused about that, since they are all in the same format, why I can't draw the graphic out using the datetime formate as xaxis??
here is my code, I cherish all your time and help!
from matplotlib import pyplot as plt
import csv
names = []
x = []
y = []
names=[]
with open('all.csv','r') as csvfile: #this csv file contains over 16000 datas
plots= csv.reader(csvfile,delimiter=',')
for row in plots:
x.append(row[1]) #row1 is the datetime format data
y.append(row[2])
print(x,y)
plt.plot(x,y)
plt.show()
Lines of my csv file look something like:
2016/05/02 10:47:45,14.1,20.1,N.C.,170.7,518.3,-1259,-12.61,375.8,44.92,13.76,92.74,132.6,38.86,165.3,170.9,311.5,252.3,501.2,447.2,378.4,35.48,7.868,181.2,
I want the first column as xaxis and the following colums as yaxis...
and the y axis doesn't change, no matter how I change the y axis limit.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('all.csv')
x = df.iloc[:,1]
y = df.iloc[:,3]
x = pd.to_datetime(x)
plt.figure(num=3, figsize=(15, 5))
plt.plot(x,y)
my_y_ticks = np.arange(0, 40, 10)
plt.xticks(rotation = 90)
plt.show()
I havent understood exactly what you mean with all the datas' format are list, but I think you could use something like this:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('all.csv')
x = df.iloc[:,0]
y = df.iloc[:,1]
x = pd.to_datetime(x)
plt.plot(x,y)
plt.show()
Maybe showing some rows can be useful
EDIT:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.read_csv('all.csv')
x = df.iloc[:,0]
y = df.iloc[:,1]
x = pd.to_datetime(x, format="%Y/%m/%d %H/%M/%S") #if the format is different, change here
fig, ax = plt.subplots()
ax.plot(x, y)
xfmt = mdates.DateFormatter("%Y/%m/%d %H:%M:%S")
ax.xaxis.set_major_formatter(xfmt)
plt.xticks(rotation=70)
plt.show()
I am trying to create a trendline on financial stock data using the following code and getting all kinds of errors. Any suggestions are most appreciated.
import pandas as pd
from pandas_datareader import data
import numpy as np
import matplotlib.pyplot as plt
df = data.DataReader(name = "GHC", data_source = "google", start = "2010-01-01", end = "2017-11-01")
#reset the index
df['ID'] = " "
df.reset_index(inplace = True)
df.set_index("ID", inplace = True)
#print(df.head(10))
#create new df for plotting
data = df[['Date', 'Close']]
#print(data.head(10))
#plot stock data
x = data['Date']
y = data['Close']
plt.scatter(x, y)
#create and plot a trendline
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x, p(x), "r--")
plt.show()
mylist = [1, 2, 3, 4, 5, 6, 7]
N = 3
cumsum, moving_aves = [0], []
for i, x in enumerate(mylist, 1):
cumsum.append(cumsum[i-1] + x)
if i>=N:
moving_ave = (cumsum[i] - cumsum[i-N])/N
#can do stuff with moving_ave here
moving_aves.append(moving_ave)
I came up with this solution:
import pandas as pd
from pandas_datareader import data
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 25,16
from datetime import datetime
%matplotlib inline
df = data.DataReader(name = "GHC", data_source = "google", start = "2017-01-01", end = "2017-11-01")
x = list(range(0, len(df.index.tolist()), 1))
y = df['Close']
date_x = df.index
fit = np.polyfit(x,y, 1)
fit_fn = np.poly1d(fit)
plt.plot(date_x, fit_fn(x), 'k-')
plt.plot(date_x, y, 'go', ms=2)
But now the dates on the x axis don't come out right. Any suggestions on how to keep the original format of 2017-01-01 etc?
I have a list of pandas dataframes, with the dataframes representing subsequent frames in a process. As such, the dataframes are all of the same size and structure (same columns and indices). I am wondering if there is a way to animate these dataframes and save the animation as mpeg movie.
I have tried to do the following, however, did not have any luck:
#X: a list of 1000 dataframe, all of same size
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(X,interpolation='nearest')
def update_img(n):
im.set_data(n.values)
return im
animation = animation.FuncAnimation(fig,update_img, frames = X, interval=30)
the above gets stuck in the first frame.
To save the animation as mp4, you can use
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np; np.random.seed(1)
import pandas as pd
X = [pd.DataFrame(np.random.rand(10,10)) for i in range(100)]
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(X[0],interpolation='nearest')
def update_img(n):
im.set_data(n.values)
ani = matplotlib.animation.FuncAnimation(fig,update_img, frames = X, interval=30)
FFwriter = matplotlib.animation.FFMpegWriter(fps=30)
ani.save(__file__+".mp4",writer = FFwriter)
plt.show()
Here is the plot I have currently:
The 'time' strings I import are like this: 08:12:46, so I would like to cut the zeros at the end, but I can't seem to find the problem. Also, is there a way to show the floats on the Y axis in the exponential format, which is the one I am importing from the csv?
I just started to look into matplotlib and numpy for work, so if you have some advice it would be fantastic.
Thank you in advance!
import numpy as np
import datetime as dt
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
print(plt.style.available)
style.use('ggplot')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
graph_data = open('C:\\Users\\arzuffi pc test\\Desktop\\VMI WIP - Copia (2)\\Cycle info\\_Current Cycle.csv','r').read()
#graph_data = open('C:\\Users\\arzuffi pc test\\Desktop\\Visual Machine Interface Alpha 1.4.3\\Cycle info\\_Current Cycle.csv','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
skip = 0
for line in lines:
if skip < 7:
skip += 1
else:
if len(line) > 1:
time, cycle, pc, pd, co, hv, cr, ph, gd_volt, gd_amp, gd_power, eva_amp, eva_volt, p_rpm, p_amp, r1_rpm, r1_amp, r2_rpm, r2_amp, hmdso, gas, ahc, diff_l, diff_r = line.split(';')
#x, y = line.split(';')
print(time)
print(pc)
xs.append(dt.datetime.strptime(time,'%H:%M:%S'))#.date())
ys.append(pc)
#print(i)
#xs = matplotlib.dates.date2num(xs)
print(xs)
if len (xs) > 100:
xs = xs[-100:]
if len (ys) > 100:
ys = ys[-100:]
ax1.clear()
ax1.plot(xs, ys)
plt.gcf().autofmt_xdate()
ani = animation.FuncAnimation(fig, animate,interval = 1000)
plt.show()
these are the data:
You can specify the format to be used as follows:
xs = matplotlib.dates.date2num(xs) # You need to keep this line
hfmt = matplotlib.dates.DateFormatter('%H:%M:%S')
ax1.xaxis.set_major_formatter(hfmt)
ax1.plot(xs, ys) # You have this already
This would give you an output as follows:
I'm trying to animate some quivers on a basemap using Numpy, but the data is on differents files (E and N gps displacements). In first place, I try to load all the files with np.loadtxt and glob, and the result it's an array (or matrix, at this point I don't know) of this style:
bla = [array([1,2,3,....,1000]), array([1,2,3,....,1000]),....]
What I want, is to animate quivers of the displacement of the gps data in a basemap, for that I made this code:
import numpy as np
from glob import glob
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.animation as animation
estaE = glob('/Users/joaquinjulve/Documents/Universidad/Herramientas/Examen/GPS_E/*e.out')
gpsE = [np.loadtxt(a) for a in estaE]
estaN = glob('/Users/joaquinjulve/Documents/Universidad/Herramientas/Examen/GPS_N/*n.out')
gpsN = [np.loadtxt(b) for b in estaN]
estaciones = np.loadtxt('/Users/joaquinjulve/Documents/Universidad/Herramientas/Examen/estaciones.coord.out', usecols=(1,2))
gpsupE = np.asarray(gpsE)
gpsupN = np.asarray(gpsN)
desE = [a.T[1] for a in gpsE]
desN = [b.T[1] for b in gpsN]
t = [c.T[0]for c in gpsE]
tup = np.asarray(t)
desupE = np.asarray(desE)
desupN = np.asarray(desN)
map = Basemap(projection='merc',
llcrnrlat=-45, llcrnrlon=-75,
urcrnrlat=-25, urcrnrlon=-60, resolution=None)
map.drawparallels(np.arange(-90,90.,4), labels=[1,0,0,0])
map.drawmeridians(np.arange(-180,180,4), labels=[0,0,0,1])
map.bluemarble(scale=4)
lat = estaciones.T[0]
lon = estaciones.T[1]
x, y = map(lon, lat)
Q = map.quiver(x, y, desupE, desupN, color='red')
def update_quiver(Q, x, y):
U = desupE
V = desupN
Q.set_UVC(U,V)
anim = animation.FuncAnimation(map, update_quiver, fargs=(Q, x, y),
interval=10, blit=True)
plt.show()