I couldn't plot graph using matplotlib values from file - python

I want to plot ECG graph using matplotlib . y values from a file having float values and x value is incrementing(ie x ranges from 1 to 1000). went through tutorials and couldn't find any solutions.

Demo Code
import numpy as np
import matplotlib.pyplot as plt
import random
import pickle
#Y Axis : Generate 1000 random numbers
yAxisNumbers = np.random.uniform(1,100,1000)
#Save numbers to a file for demo purpose
with open('numpyData.txt', 'wb') as myFile:
pickle.dump(yAxisNumbers,myFile)
#X Axis :Generate 1000 random numbers
xNumbers = [ x for x in range(1000)]
#Load file data to a list
with open('numpyData.txt', 'rb') as aFile:
yNumbers = pickle.load(aFile)
#Plot and label Graph
plt.plot(xNumbers,yNumbers)
plt.ylabel("Random Float Numbers")
plt.xlabel("Number Count")
plt.title("ECG Graph")
plt.show()
Graph

Here's a minimal answer, based on the scant details provided.
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
Y = np.loadtxt(filename, other needed options)
plt.plot(np.arange(len(Y))+1,Y)

import numpy as np
import pylab as p
aa=np.loadtxt('....your file ....')
x,y= aa.T # transpose data into 2 columns, assuming you have 2 columns
p.plot(x,y)
p.show()

Related

Emplty plot normalised values

Want to plot normalised values in array but getting empty plot
import numpy as np
x_array = np.array([2,3,5,6,7,4,8,7,6])
normalized_arr = preprocessing.normalize([x_array])
print(normalized_arr)
plt.plot(normalized_arr)
plt.show()
Empty plot - https://i.stack.imgur.com/NnSbI.png
Is there function that can fill the empty plot with values?
You probably need to change your code into:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
x_array = np.array([2,3,5,6,7,4,8,7,6])
normalized_arr = preprocessing.normalize([x_array])
print(normalized_arr)
plt.plot(x_array.reshape(-1,1),normalized_arr.reshape(-1,1))
plt.show()
Output

Plotting tendency line in Python

I want to plot a tendency line on top of a data plot. This must be simple but I have not been able to figure out how to get to it.
Let us say I have the following:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
sns.lineplot(data=df)
ax.set(xlabel="Index",
ylabel="Variable",
title="Sample")
plt.show()
The resulting plot is:
What I would like to add is a tendency line. Something like the red line in the following:
I thank you for any feedback.
A moving average is one method (my first thought, and already suggested).
Another method is to use a polynomial fit. Since you had 100 points in your original data, I picked a 10th order fit (square root of data length) in the example below. With some modification of your original code:
idx = [i for i in range(100)]
rnd = np.random.randint(0,100,size=100)
ser = pd.Series(rnd, idx)
fit = np.polyfit(idx, rnd, 10)
pf = np.poly1d(fit)
plt.plot(idx, rnd, 'b', idx, pf(idx), 'r')
This code provides a plot like this:
You can do something like this using Rolling Average:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.randint(0,100,size=(100, 1))
df["rolling_avg"] = df.A.rolling(7).mean().shift(-3)
sns.lineplot(data=df)
plt.show()
You could also do a Regression plot to analyse how data can be interpolated using:
ax = sns.regplot(x=df.index, y="A",
data=df,
scatter_kws={"s": 10},
order=10,
ci=None)

ValueError: x and y must be the same size for 2D nparray matrix

%matplotlib inline
from sklearn.datasets import load_svmlight_file
import numpy as np
import matplotlib.pyplot as plt
Xtr,Ytr = load_svmlight_file("a9a")
Xtst,Ytst = load_svmlight_file("a9a.t")
Xtr=Xtr.todense()
Xtst=Xtst.todense()
print (Xtr.shape, "", Ytr.shape)
The Output was
Xtr = (32561,123)
Ytr = (32561,)
I want to plot this on a scatter graph . But I receive an error which says Xtr and Ytr are not of the same size . How do I make them same size .
Which column of Xtr do you want to plot? It has 123 columns, so you'll have to choose only one of them.

Python plotting lines parallel to y axis from array

I have an array containing 5 different numbers:
array([2.40064633, 4.10132553, 8.59968518, 2.40290345, 1.39988773]
and I want to plot the lines on the x axis (parallel to the y axis) equal to each of these numbers i.e.
x = 2.4006463
x = 4.10132553 so on and so forth for all of the numbers in the array.
I tried using plot(x = array[...]) but to no solution.
Is there a clean way of doing this using numpy or mathlab?
This will work:
import matplotlib.pyplot as plt
b =([2.40064633, 4.10132553, 8.59968518, 2.40290345, 1.39988773])
for l in b:
plt.axvline(l)
plt.show()
or is it an numpy array then:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1,4)
for l in x:
plt.axvline(l)
plt.show()
here is my take. quite the similar as Rahul's only with the lines harshed.
import matplotlib.pyplot as plt
import numpy as np
xcoords = np.array([2.40064633, 4.10132553, 8.59968518, 2.40290345, 1.39988773])
for xc in xcoords:
plt.axvline(x=xc, color='k', linestyle='--')

how to modify the autocorrelation default plot style and write the output of a acorr function to a dat/txt file?

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab`
mu = np.loadtxt('my_data/corr.txt')
d = mu[:,2]
y=[]
tot=0
min=999
for i in d:
y.append(float(i))
tot=tot+float(i)
if (min>float(i)):
min=float(i)
av=tot/len(y)
z=[]
m=[]
for i in y:
z.append(i-av)
m.append(i-min)
plt.acorr(z,usevlines=True,maxlags=None,normed=True)
plt.show()
WIth this code I have the output showing a bar chart.
Now,
1) How do I change this plot style to give just the trend line? I cant modify the line properties by any means.
2) How do I write this output data to a dat or txt file?
this should be a working minimal example:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import normal
data = normal(0, 1, 1000)
# return values are lags, correlation vector and the drawn line
lags, corr, line, rest = plt.acorr(data, marker=None, linestyle='-', color='red', usevlines=False)
plt.show()
np.savetxt("correlations.txt", np.transpose((lags, corr)), header='Lags\tCorrelation')
But i would recommand not to connect the points.

Categories