matplotlib Help using python 2.7 - python-2.7

Hi I am trying to make a scatter plot and annotate data points with real value of each point
but just the yLabel value
it mean take real value of the point and plot it near to the point
python code
import serial # import Serial Library
import time #import time
import numpy # Import numpy
import matplotlib.pyplot as plt #import matplotlib library
from drawnow import *
temperature= []
vitesse= []
charge= []
current= []
arduinoData = serial.Serial('com5', 9600) #Creating our serial object named arduinoData
plt.ion() #Tell matplotlib you want interactive mode to plot live data
cnt=0
def makeFig(): #Create a function that makes our desired plot
plt.subplot(2,2,1)
plt.title('Live Streaming Temperature Sensor Data')
plt.ylabel('Temperature C')
plt.grid(True)
plt.plot(temperature, 'ro-')
plt.subplot(2,2,2)
plt.title('Live Streaming Speed Sensor Data')
plt.ylabel('Speed KM/H')
plt.grid(True)
plt.plot(vitesse, 'bo-')
plt.subplot(2,2,3)
plt.title('Live Streaming SOC Sensor Data')
plt.ylabel('Battery Charge %')
plt.grid(True)
plt.plot(charge, 'go-')
plt.subplot(2,2,4)
plt.title('Live Streaming Current Sensor Data')
plt.ylabel('Current A')
plt.grid(True)
plt.plot(current, 'yo-')
while True: # While loop that loops forever
while (arduinoData.inWaiting()==0): #Wait here until there is data
pass #do nothing
arduinoString = arduinoData.readline() #read the line of text from the serial port
dataArray = arduinoString.split(';') #Split it into an array called dataArray
temp = float (dataArray[0])
vite = float (dataArray[1])
char = float (dataArray[2])
curr = float (dataArray[3])
temperature.append(temp) #Build our temperature array by appending temp readings
vitesse.append(vite) #Build our vitesse array by appending temp readings
charge.append(char) #Build our charge array by appending temp readings
current.append(curr) #Build our current array by appending temp readings
drawnow(makeFig) #Call drawnow to update our live graph
plt.pause(0.00001)
cnt=cnt+1
if(cnt>50):
temperature.pop(0)
vitesse.pop(0)
charge.pop(0)
current.pop(0)
any ideas ?????

use the annotate() function to create labels attached to specific points in your plot.
see http://matplotlib.org/users/annotations_intro.html
and http://matplotlib.org/examples/pylab_examples/annotation_demo2.html

If I understood what you were looking for, you should use plt.ticklabel_format(useOffset=False) at the end of every subplot. So that, you are going to fix the y scale. Use plt.ylim(m,n) to set the limits of the y axe, where "m" is the beggining of the axe and "n" is the end.

Related

Python24: Maplotlib Animation connecting the first and the last point

I am new to matplotlib and I was playing with this library to plot data from a csv file. Without using the animation function the graph looks correct, but When I tried to use the animation, the graph connected the first and the last point. I looked stuff up, but I can't figure out how to solve this. Does anyone know how to solve this issue? Below is my code. Thanks in advance!
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import csv
x = []
y = []
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
with open("example.txt", "r") as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(int(row[0]))
y.append(int(row[1]))
ax1.clear()
ax1.plot(x,y)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
You append all the same points over and over again to the lists to plot. So say the csv file contains numbers 1,2,3 what you are doing is reading them in, appending them to the list, plotting them, then reading them in again and appending them etc.
So x contains in
Step 1 : 1,2,3
Step 2 : 1,2,3,1,2,3
Step 3 : 1,2,3,1,2,3,1,2,3
Hence from step 2 on there will be a connection between 3 and 1.
I don't know what the purpose of this animation is since animating all the same points is quite useless. So there is no straight forward solution, apart from not animating at all.

plotting multiple sensor values using drawnow in python

I am having 7 sensors which is connected to a micro controller , the controller a sends data to a pc using serial port , i am trying to plot the sensors values in real-time using python drawnow function , can anybody help me in giving the correct syntax for the same to plot the all the sensors in the same figure
How about this for 4 sensors:
import time
import matplotlib.pyplot as plt
from drawnow import *
sensors = 4
x = dict([(s,[]) for s in range(0,sensors)]) # initialize dictionary of sensor stream values
def makePlot():
plt.subplot(411)
plt.plot(x[0],'r')
plt.subplot(412)
plt.plot(x[1],'g')
plt.subplot(413)
plt.plot(x[2],'b')
plt.subplot(414)
plt.plot(x[3],'c')
for i in range(0,100): # simulate passage of time
time.sleep(1) # 1-sec delay for each loop
for s in range(0,sensors):
x[s].append(i*s)
drawnow(makePlot)

How to to compute a FFT spectrum of observation data and extract the harmonics retaining the diurnal cycle?

Dear all python users,
I'm new in python and I want to use it to compute a FFT spectrum of observation data and extract the harmonics retaining the diurnal cycle. My data is composed by (time:262992 hours; site:46 stations), which is hourly air_temperature of 46 stations from 1983-2012. I have been able to plot time series of selected station (see the code below). Now I want to compute FFT spectrum of selected station (data[0] for instance), and extract the harmonic retaining the diurnal cycle. How to do it?
Python code:
import iris
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#Load the data
t_air = iris.load_cube('/home/amadou/anaconda/RainCell_python_mw_link_training/all_new.nc', 'air_temperature')
#Have a quick look
print t_air
#create a pandas data frame with each column representing a site
data=as_data_frame(t_air[:,0])
for i in range(0,t_air.coord('latitude').shape[0]):
data[str(i)]=as_data_frame(t_air[:,i])
data.head()
#create a metadata list with lat/lon (each index represents the corresponding data frame column)
metadata=[]
for i in range(0,t_air.coord('latitude').shape[0]):
lat = t_air[:,i].coord('latitude').points[0]
lon = t_air[:,i].coord('longitude').points[0]
metadata.append([lat,lon])
# now you do the pandas stuff (plotting,resampling,…)
# Example for the monthly averages of the first site
ax = data[0].resample('D')['2012-04':'2012-05'].plot(figsize=(10,5))
ax.legend([metadata[0]])
Is there anybody who can help me, from here, to compute a FFT spectrum of this data and extract the harmonics retaining the diurnal cycle?
Best

line graph from loop in Python

Helo everyone
I need some help. I wrote this scrip:
import matplotlib.pyplot as plt
import scipy
import pyfits
import numpy as np
import re
import os
import glob
import time
global numbers
numbers=re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
image_list=sorted(glob.glob('*.fit'), key=numericalSort)
for i in range(len(image_list)):
hdulist=pyfits.open(image_list[i])
data=hdulist[0].data
dimension=hdulist[0].header['NAXIS1']
time=hdulist[0].header['TIME']
hours=float(time[:2])*3600
minutes=float(time[3:5])*60
sec=float(time[6:])
cas=hours+minutes+sec
y=[]
for n in range(0,dimension):
y.append(data.flat[n])
maxy= max(y)
print image_list[i],cas,maxy
plt.plot([cas],[maxy],'bo')
plt.ion()
plt.draw()
This scrip read fit data file. From each file find max value which is y value and from header TIME which is x value axis.
And now my problem...When I run this scrip I get graph but only with points. How I get graph with line (line point to point)?
Thank for answer and help
Your problem may well be here:
plt.plot([cas],[maxy],'bo')
at the point that this statement is encountered, cas is a single value and maxy is also a single value -- you have only one point to plot and therefore nothing to join. Next time round the loop you plot another single point, unconnected to the previous one, and so on.
I can't be sure, but perhaps you mean to do something like:
x = []
for i in range(len(image_list)):
hdulist=pyfits.open(image_list[i])
data=hdulist[0].data
dimension=hdulist[0].header['NAXIS1']
time=hdulist[0].header['TIME']
hours=float(time[:2])*3600
minutes=float(time[3:5])*60
sec=float(time[6:])
cas=hours+minutes+sec
x.append(cas)
y=[]
for n in range(0,dimension):
y.append(data.flat[n])
maxy= max(y)
print image_list[i],cas,maxy
plt.plot(x, y ,'bo-')
plt.ion()
plt.draw()
ie plot a single line once you've collected all the x and y values. The linestyle format, bo- which provides the connecting line.
OK here is solution
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import scipy
import pyfits
import numpy as np
import re
import os
import glob
import time
global numbers
numbers=re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
def animate(i):
image_list=sorted(glob.glob('*.fit'), key=numericalSort)
cas,maxy=[],[]
files=open("data.dat","wr")
for n in range(len(image_list)):
hdulist=pyfits.open(image_list[n])
data=hdulist[0].data
maxy=data.max()
time=hdulist[0].header['TIME']
hours=int(float(time[:2])*3600)
minutes=int(float(time[3:5])*60)
sec=int(float(time[6:]))
cas=hours+minutes+sec
files.write("\n{},{}".format(cas,maxy))
files.close()
pool=open('data.dat','r')
data=pool.read()
dataA=data.split('\n')
xar=[]
yar=[]
pool.close()
for line in dataA:
if len(line)>1:
x,y=line.split(',')
xar.append(int(x))
yar.append(int(y))
print xar,yar
ax1.clear()
ax1.plot(xar,yar,'b-')
ax1.plot(xar,yar,'ro')
plt.title('Light curve')
plt.xlabel('TIME')
plt.ylabel('Max intensity')
plt.grid()
This script read some values from files and plot it.

Animation figure closing when interval is increased (FuncAnimation)/Explainantion of interval in FuncAnimation

I am trying write a program for 1D FDTD wave propagation, everything is fine except the interval keyword argument of FuncAnimation. Whenever I increase the interval from 10 (19 to be precise), the animation figure closes before running (exits as soon as it pops up). Now i can easily slow down the animation using time.sleep, but it would be great if i could understand this. Can somebody please explain me how this interval argument works. Is it, in anyway related to the time required by the function that updates frames which is being called by FuncAnimation? Also what is blit for?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def main():
#defining dimensions
xdim=720
time_tot = 500
xsource = xdim/2
#stability factor
S=1
#Speed of light
c=1
epsilon0=1
mu0=1
delta =1 # Space step
deltat = S*delta/c # Time step
Ez = np.zeros(xdim) # Arrays to store Electric field and magnetic field
Hy = np.zeros(xdim)
epsilon = epsilon0*np.ones(xdim) #Permittivity and permeability values.
mu = mu0*np.ones(xdim)
fig , axis = plt.subplots(1,1)
axis.set_xlim(len(Ez))
axis.set_ylim(-3,3)
axis.set_title("E Field")
line, = axis.plot([],[])
def init():
line.set_data([],[])
return line,
def animate(n, *args, **kwargs):
Hy[0:xdim-1] = Hy[0:xdim-1]+(delta/(delta*mu[0:xdim-1]))*(Ez[1:xdim]-Ez[0:xdim-1])
Ez[1:xdim]= Ez[1:xdim]+(delta/(delta*epsilon[1:xdim]))*(Hy[1:xdim]-Hy[0:xdim-1])
#Ez[xsource] = Ez[xsource] + 30.0*(1/np.sqrt(2*np.pi))*np.exp(-(n-80.0)**2/(100))
Ez[xsource]=np.sin(2*n*np.pi/180)
ylims = axis.get_ylim()
if (abs(np.amax(Ez))>ylims[1]): # Scaling axis
axis.set_ylim(-(np.amax(Ez)+2),np.amax(Ez)+2)
line.set_data(np.arange(len(Ez)),Ez)
return line,
ani = animation.FuncAnimation(fig, animate, init_func=init, frames=(time_tot), interval=10, blit=False, repeat =False)
fig.show()
if __name__ == "__main__": main()