I have two txt files. The datas in the first one are :
0
0.1
0.5
0.3
and in the second one are:
20
32
35
39
So what I wanna do is:
1º read both text files 2º save the differents values in a vector. 3º plot
In this moment I have done the following code:
fichero = open('signal1t.txt','r')
listx = []
for linea in fichero:
listx.append(linea.strip() )
fichero = open('signal2.txt','r')
listy = []
for linea in fichero:
listay.append(linea.strip() )
But the problem is that it doesn't run very well. In fact it doesn't save numbers ...
Is there anybody that can help me?
a simpler solution is tu use numpy :
import numpy as np
listx=np.loadtxt('signal1t.txt')
listy=np.loadtxt('signal2t.txt')
Then you just have to plot using matplotlib:
import matplotlib.pyplot as plt
plt.plot(listx,listy)
plt.show()
You have to typecast the read string to float:
listx.append(float(linea.strip()))
What you wish to do is very simple with numpy and matplotlib:
import numpy as np
import matplotlib.pyplot as plt
listx = np.genfromtxt('signal1.txt')
listy = np.genfromtxt('signal2.txt')
plt.plot(listx, listy, 'x')
plt.show()
Related
I got a simple 2D array of values like this :
[simple array]
and I want to add reverb to it (I don't know how to call it other way) in order for it to look like this, basicly with a damping/smooth effect on y values but only on +x :
[with reverb]
I tried to check with scipy as i'm already using it to smooth values but didn't found out how to do it.
does anybody has an idea ?
You could try a Finite impulse response filter, though it's not clear if it's exactly what you need.
This was produced by the script below.
I've assumed, given your figures, that your data is actually 1-dimensional (a "line" of numbers, not a "rectangle").
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
npts = 50
# FIR with falling sawtooth impulse response
b = np.linspace(1,0,npts,endpoint=False)
u = np.zeros(3 * npts)
u[0] = 1
u[npts + 10] = 1
u[npts + 10 + npts//2] = 1
y = signal.lfilter(b, [1], u)
fig, ax = plt.subplots(2)
ax[0].stem(u)
ax[0].set_ylabel('input')
ax[1].stem(y)
ax[1].set_ylabel('output')
plt.show()
I searched online and couldn't find anything about this that does what I want.
I would like to save a numpy array as an image but instead of having a colorful image, I want a black and white representation of the pixel values in their corresponding grid location.
For example:
import numpy as np
x = np.array([[1,2],[3,4]])
print(x)
# [[1 2]
# [3 4]]
I would like to save this as an image (.PNG) that looks like the following:
My current code creates a grid and places the numbers inside but it is very difficult to adjust everything to make it presentable in a research paper.
So rather than posting my overly complex code, I was wondering if there is a built in function to handle this in a few lines of code.
I would use LaTeX to generate the tables, since they look fancy and you can either generate an image or directly put them in your document. I used the following code to achieve this:
#!/usr/bin/env
import numpy as np
import os
x = np.array([[1,2],[3,4]])
def generateLatexTable(x):
start = [r'\documentclass[preview]{standalone}', r'\begin{document}', r'\begin{tabular}{%s}' % ('{1}{0}{1}'.format('|'.join(['r'] * x.shape[1]), '|')), r'\hline']
tab = [' & '.join(['%d' % val for val in row]) + r' \\ \hline' for row in x]
end = [r'\end{tabular}', r'\end{document}']
text = '\n'.join(start + tab + end)
return text
with open('table.tex', 'w') as f:
f.write(generateLatexTable(x))
os.system("pdflatex table.tex")
Here, the document class preview is used which returns an image resized to the content of the document, i.e. just the table. Only a tabular environment is used to present the data. There are horizontal and vertical bars between the cells, but it is very easy to change this. In the variable tab the data is processed for each row and converted into a string. Note that you have to specify the output format at this position. I set it to %d so everything is converted to integers.
If you want to use the table directly in a latex source, you have to remove documentclass and \begin{document} as well as \end{document} in the variables of start and end. Finally, everything is put together in a latex-source which is then stored to disk as table.tex. If you just want the image in the end, the resulting file is compiled to table.pdf.
Here is what the output looks like. But like I said, it is very easy to change the looks since it is LaTeX :)
Here is another example with a large matrix (14 x 14), filled with random numbers ranging from 0 to 100:
You can use the table function of matplot to plot the simple table. Furthermore, you can save the plot as PNG.
Below is the simple code for your requirements:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,2],[3,4]])
plt.figure()
plt.table(cellText=x,cellLoc='center',loc='center')
plt.axis('off')
plt.savefig('table.png')
Size of the plot or image can be adjusted by changing figsize parameters in the line : plt.figure(figsize=(x,y))
For better appearance, it can be modified as below:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[1,2],[3,4]])
fig = plt.figure(figsize=(2,2))
plt.axis('off')
plt.axis('tight')
plt.table(cellText=x,cellLoc='center',loc='center')
#plt.subplots_adjust(hspace=0.5)
fig.tight_layout()
plt.savefig('table.png')
May be this will help:
from matplotlib import pyplot as plt
import numpy as np
w = 10
h = 10
img = np.random.randint(255, size=(w, h))
plt.figure(figsize=(5,8))
plt.imshow(img, interpolation='nearest')
plt.axis('off')
cellTextimg = []
for j in range(0,h):
cellTextimg.append(img[j,:])
the_table = plt.table(cellText= cellTextimg, loc='bottom')
I´m trying to interpolate data from a 2D array in python using scipy.interpolate.interp2d. However, I don´t think I fully understand what it is doing ,so any help is appreciated. I am trying to do something similar to what is suggested here Link.
My code is below:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
from scipy.interpolate import griddata
p = np.array([[1,2,3,4,5,6,7,8,9,1],[1,2,3,4,5,6,7,8,9,1],
[1,6,3,4,8,6,7,8,9,1],[1,2,3,4,5,6,7,89,9,1],
[1,56,3,4,5,6,7,67,6,1],[1,2,3,4,7,6,7,8,9,1],
[1,2,3,5,5,6,7,6,9,1],[1,2,3,6,5,6,7,45,9,1],
[9,2,3,4,21,6,7,8,9,1],[1,8,3,3,5,6,7,5,9,1]])
print(pf)
mymin, mymax = 0, 9
X = np.linspace(mymin,mymax,10)
Y = np.linspace(mymin,mymax,10)
Xnew = np.linspace(mymin,mymax,20)
Ynew = np.linspace(mymin,mymax,20)
f = interpolate.interp2d(x,y,p,kind='cubic')
Po = f(Xnew,Ynew)
print(Po)
When I run it, the following error message is displayed:
ValueError: Invalid length for input z for non rectangular grid
This is what I have tried so far
import itertools
import numpy as np
import matplotlib.pyplot as plt
with open('base.txt','r') as f:
vst = map(int, itertools.imap(float, f))
v1=vst[::3]
print type(v1)
a=np.asarray(v1)
print len(a)
a11=a.reshape(50,100)
plt.imshow(a11, cmap='hot')
plt.colorbar()
plt.show()
I have (50,100) array and each element has numerical value(range 1200-5400).I would like to have image that would represent array.But I got this
What should I change to get proper image?
I don't have data from base.txt.
However, in order to simulate your problem, I created random numbers between 1500 to 5500 and created a 50 x 100 numpy array , which I believe is close to your data and requirement.
Then I simply plotted the data as per your plot code.
I am getting true representation of the array.
See if this helps.
Demo Code
#import itertools
import numpy as np
from numpy import array
import matplotlib.pyplot as plt
import random
#Generate a list of 5000 int between 1200,5500
M = 5000
myList = [random.randrange(1200,5500) for i in xrange(0,M)]
#Convert to 50 x 100 list
n = 50
newList = [myList[i:i+n] for i in range(0, len(myList), n)]
#Convert to 50 x 100 numpy array
nArray = array(newList)
print nArray
a11=nArray.reshape(50,100)
plt.imshow(a11, cmap='hot')
plt.colorbar()
plt.show()
Plot
In Python, how can I import data that looks like this:
waveform [0]
t0 26/11/2014 10:53:03.639218
delta t 2.000000E-5
time[0] Y[0]
26/11/2014 10:53:03.639218 1.700977E-2
26/11/2014 10:53:03.639238 2.835937E-4
26/11/2014 10:53:03.639258 2.835937E-4
26/11/2014 10:53:03.639278 -8.079492E-3
There are two delimiters, : and white space. I want to get rid of the date 24/11/2014 and delete the semicolons so that the time array looks like 105303.639218, etc. So is there a way to specify two delimiters in the code, or is there a better way to analyse the data?
So far I have got:
import numpy as np
import matplotlib.pyplot as plt
_, time, y = np.loadtxt('data.txt', delimiter=':', skiprows=5)
plt.plot(time,y)
plt.show()
You can do this:
time = '10:34:20.454068'
list_ = time.split(':')
''.join(list_)
# '103420.454068'
for each row.
Maybe it's sort of a roundabout way of doing this, but...
import numpy as np
import matplotlib.pyplot as plt
mydata = np.loadtxt('data.txt', dtype='string', skiprows=5)
time = mydata[:,1]
time = np.array([s.replace(':','') for s in time])
y = np.array(mydata[:,2])
plt.plot(time,y)
plt.show()