Matplotlib - when plotting time it puts decimal zeros after the seconds - python

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:

Related

How to remove baseline drift after denoising the signal?

I want to plot a cardiac signal from forrestgump dataset in openneuro.I opened the tsv. file and I plot the signal.then I removed the noise by a median filter.But the signal in my opinion has baseline drift.I can't find out how I can remove the baseline drift from the figure.the figure must be straight in x axis
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
import csv
import math
x = []
y = []
tsv_file ='tsvfile'
with open(tsv_file, 'r') as tsvfile:
lines = csv.reader(tsvfile, delimiter=" ")
for index, row in enumerate(lines):
x.append(index)
y.append(row[2])
window_size = 200
i = 0
moving_averages = []
yy=np.array(y).astype(np.float)
print(len(yy))
while i < len(yy) - window_size + 1:
window_average = np.sum(yy[i:i+window_size])/window_size
moving_averages.append(window_average)
i += 1
yd=moving_averages
xd = np.arange(len(yd))
print(len(yd))
plt.plot(xd[0:2000], yd[0:2000], color='g', linestyle='dashed', marker='.', label="Weather Data")
plt.show()

Pendulum plot simulation Matplotlib - data from file

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.

Change matplotlib offset notation from scientific to plain

I want to set the formatting of the y-axis offset in my plot to non-scientific notation, but I can't find a setting to do this. Other questions and their solutions describe how to either remove the offset altogether, or set the y-ticks to scientific/plain notation; I haven't found an answer for setting the notation of the offset itself.
I've already tried using these two options, but I think they're meant for the y-ticks, not the offsets:
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
and
ax.get_yaxis().get_major_formatter().set_scientific(False)
So, the actual result is +6.3781e3, when I want +6378.1
Any way to do this?
Edit: Added example code and figure:
#!/usr/bin/env python
from matplotlib import pyplot as plt
from matplotlib import ticker
plt.rcParams['font.family'] = 'monospace'
import random
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()
You can subclass the default ScalarFormatter and replace the get_offset method, such that it would simply return the offset as it is. Note that if you wanted to make this compatible with the multiplicative "offset", this solution would need to be adapted (currently it just prints a warning).
from matplotlib import pyplot as plt
import matplotlib.ticker
import random
class PlainOffsetScalarFormatter(matplotlib.ticker.ScalarFormatter):
def get_offset(self):
if len(self.locs) == 0:
return ''
if self.orderOfMagnitude:
print("Your plot will likely be labelled incorrectly")
return self.offset
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.yaxis.set_major_formatter(PlainOffsetScalarFormatter())
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()
A way to do this is to disable the offset text itself and add your custom ax.text there as follows
from matplotlib import pyplot as plt
import random
plt.rcParams['font.family'] = 'monospace'
offset = 6378.1
Date = range(10)
R = [offset+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.ticklabel_format(axis='y', style='plain', useOffset=offset)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
ax.yaxis.offsetText.set_visible(False)
ax.text(x = 0.0, y = 1.01, s = str(offset), transform=ax.transAxes)
plt.show()

Problem when using datetime data to draw graphic

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()

Plot Time values with matplotlib

I have a sample text file as follows:(test.txt)
06:00:41 2
06:10:41 4
06:20:41 6
06:25:41 8
I want to plot this taking time value for X-Axis and the 2nd column to the y axis.
import matplotlib.pyplot as plt
import datetime
import matplotlib.dates as mdates
import time
import numpy as np
f2 = open('test.txt', 'r')
lines = f2.readlines()
f2.close()
x1 = []
y1 = []
for line in lines:
p = line.split()
a = time.strptime((p[0]),"%H:%M:%S")
x1.append((a))
y1.append(float(p[1]))
xv = np.array(x1)
yv = np.array(y1)
plt.plot(xv, yv)
plt.show()
This is how I plot it. But the X-Axis shows 500,1000,1500 etc. Instead I want to show the time values as 06:00:41,06:10:41,06:20:41 etc. Please help me?
Have you tried plot_date?
It may help if you put your time series data as datetime values
from datetime import datetime
for line in lines:
p = line.split()
xv.append(datetime.strptime(p[0], '%H:%M:%S'))
fig, ax = plt.subplots()
ax.plot_date(xv, yv)
If you want a line plot, try changing the linestyle (docs)
ax.plot_date(xv, yv, linestyle='-')

Categories