I want to plot any part or the data
here is the code
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
... ...
xs = []
avg = []
for line in lines:
if len(line) > 1:
x, y1 = line.split(',')
xs.append(float(x))
avg.append(float(y1))
ax1.plot(xs, avg, label='avg')
I added some of the code so you can see the type of the variables
I tried :
ax1.plot(xs[avg>0], avg[avg>0], label='avg')
and didnt work
im matlab i would do some thing like :
Indxs=find (ys>0)
Plot(xs(indxs),ys(indxs))
The syntax is correct. The problem is that xs and avg are no numpy arrays. So you first need to convert those lists to numpy arrays, then the slicing will work as expected.
xs = np.array(xs)
avg = np.array(avg)
ax1.plot(xs[avg>0], avg[avg>0], label='avg')
What you doesen't work since your index (avg > 0) in python is a boolean. When you are used to Matlab then you should definitely try numpy Boolean indexing.
you can do:
import numpy as np
xs = numpy.asarray(x)
ys = numpy.asarray(y)
ys_filtered = ys[x > 0]
Related
I have a file abc.dat having data set with column "ec", "ev", "eig", "ep". I have to plot E vs x graph. Here the values for x, E and other variables related to this are given below.
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('/Users/abc.dat')
ec = data[0:,0]
ev = data[0:,1]
eig = data[0:,2]
ep = data[0:,3]
a=(eig-(ec-ev))
A= 5
B=1/eig**2
for x in range(1,500):
g=(1/(0.5* np.sqrt(2*3.14)))* np.exp((-(x-eig)**2)/(2*(0.5)**2))
ep_1=(ep*g)**2
P=sum(ep_1)
for i in a:
if i==0:
D=1
else:
D=0
e=A*B*P*D
plt.plot(x,e)
Your code has the plt.plot() command buried in loops, which is probably not what you are trying to do. You will need x to be an array the same size as e, and from your question it might have fewer points than you expect since it has shape (409,).
Try this:
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('/Users/abc.dat')
ec = data[0:,0]
ev = data[0:,1]
eig = data[0:,2]
ep = data[0:,3]
a=(eig-(ec-ev))
A= 5
B=1/eig**2
x = np.arange(len(eig))
g=(1/(0.5* np.sqrt(2*3.14)))* np.exp((-(x-eig)**2)/(2*(0.5)**2))
P=((g*np.broadcast_to(ep, (len(g), len(ep))).T)**2).sum(axis=0)
e=np.where(a==0, A*B*P, 0)
plt.plot(x,e)
I am not sure from the question if I have the logic for P calculating as you want it to.
How to execute this code:
import numpy as np
import math
x = np.arange(1,9, 0.5)
k = math.cos(x)
print(x)
I got an error like this:
TypeError: only size-1 arrays can be converted to Python scalars
Thank you in advance.
So this is happening because math.cos doesn't accept numpy arrays larger than size 1. That's why if you had a np array of size 1, your approach would still work.
A simpler way you can achieve the result is to use np.cos(x) directly:
import numpy as np
x = np.arange(1,9, 0.5)
k = np.cos(x)
print(x)
print(k)
If you have to use the math module, you can try iterating through the array and applying math.cos to each member of the array:
import numpy as np
import math
x = np.arange(1,9,0.5)
for item in x:
k = math.cos(item)
print(k) # or add to a new array/list
You're looking for something like this?
import numpy as np
import math
x = np.arange(1,9, 0.5)
for ang in x:
k = math.cos(ang)
print(k)
You are trying to pass ndarray (returned by arange) to a function, which expects just real number. Use np.cos instead.
If you want pure-Python:
You can use math.fun in map like below:
import math
x = range(1,9)
print(list(map(math.cos, x)))
Output:
[0.5403023058681398, -0.4161468365471424, -0.9899924966004454, -0.6536436208636119, 0.2836621854632263, 0.9601702866503661, 0.7539022543433046, -0.14550003380861354]
I am currently stuck on a problem on which I am required to generate a curve of best fit which I am required to use a more precise x array from 250 to 100 in steps of 10. Here is my code below so far..
import numpy as np
from numpy import polyfit, polyval
import matplotlib.pyplot as plt
x = [250,300,350,400,450,500,550,600,700,750,800,900,1000]
x = np.array(x)
y = [0.791, 0.846, 0.895, 0.939, 0.978, 1.014, 1.046, 1.075, 1.102, 1.148, 1.169, 1.204, 1.234]
y= np.array(y)
r = polyfit(x,y,3)
fit = polyval(r, x)
plt.plot(x, fit, 'b')
plt.plot(x,y, color = 'r', marker = 'x')
plt.show()
If I understand correctly, you are trying to create an array of numbers from a to b by steps of c.
With pure python you can use:
list(range(a, b, c)) #in your case list(range(250, 1000, 10))
Or, since you are using numpy you can directly make the numpy array:
np.arange(a, b, c)
To create an array in steps you can use numpy.arange([start,] stop[, step]):
import numpy as np
x = np.arange(250,1000,10)
To generate values from 250-1000, use range(start, stop, step):
x = range(250,1001,10)
x = np.array(x)
How would I setup this plot up in Python?
Here is what I do in Mathematica:
mykvalue = Table[k, {k, 0, 10, 1}];
u[r_, k_] = 1/(2*r^2) + k/(2*r^2);
Plot[u[r, mykvalue], {r, 0, 5}, PlotStyle -> {Red},
PlotRange -> {{0, 5}, {0, 2}}]
in my opinion one of the simplest way to do it would be to use a multidimensional list to store the values and than plot using matplotlib. this is what i mean
from math import *
import numpy as np
import matplotlib.pyplot as plt
k = range(11)
yvals = [[] for i in range(len(k))] #there should be a more pythonic way to
x = np.arange(0.4,5,0.1) #create nested lists i think, ALM I added np.
for i in k:
for j in x:
i = float(i) #this conversion from int to float was to debug,
j = float(j) #it should be made better
y=1/(2*j**2) + i/(2*j**2)
i = int(i)
yvals[i].append(y)
for i in k:
plt.plot(x,yvals[i])
plt.show()
that should work i guess. you can fiddle around with matplotlib to fix the axes and get labels and stuff.
From the Matplotlib gallery - and they show the source code.
This is close:
http://matplotlib.org/examples/pylab_examples/errorbar_limits.html
http://matplotlib.org/examples/pylab_examples/step_demo.html
http://matplotlib.org/gallery.html
HTH
I need to use the "savefig" in Python to save the plot of each iteration of a while loop, and I want that the name i give to the figure contains a literal part and a numerical part. This one comes out from an array or is the number associated to the index of iteration. I make a simple example:
# index.py
from numpy import *
from pylab import *
from matplotlib import *
from matplotlib.pyplot import *
import os
x=arange(0.12,60,0.12).reshape(100,5)
y=sin(x)
i=0
while i<99
figure()
a=x[:,i]
b=y[:,i]
c=a[0]
plot(x,y,label='%s%d'%('x=',c))
savefig(#???#) #I want the name is: x='a[0]'.png
#where 'a[0]' is the value of a[0]
thanks a lot.
Well, it should be simply this:
savefig(str(a[0]))
This is a toy example. Works for me.
import pylab as pl
import numpy as np
# some data
x = np.arange(10)
pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
I had the same demand recently and figured out the solution. I modify the given code and correct several explicit errors.
from pylab import *
import matplotlib.pyplot as plt
x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0
while i < 99:
figure()
a = x[i, :] # change each row instead of column
b = y[i, :]
i += 1 # make sure to exit the while loop
flag = 'x=%s' % str(a[0]) # use the first element of list a as the name
plot(a, b, label=flag)
plt.savefig("%s.png" % flag)
Hope it helps.
Since python 3.6 you can use f-strings to format strings dynamically:
import matplotlib.pyplot as plt
for i in range(99):
plt.figure()
a = x[:, i]
b = y[:, i]
c = a[0]
plt.plot(a, b, label=f'x={c}')
plt.savefig(f'x={c}.png')