So i made this code to create a plot that should look like this[This image was done in Mathematica] 1 but for some reason nothing shows up on the plot plot i made.does it have to something with the gam(x_2) or gam itself because i tried defining that as a range but still nothing. please teach me. From the plot made in matematica it seems like he set both the x and y ranges all the way up to 10,000.
import matplotlib.pyplot as plt
import numpy as np
import math
import pylab
%matplotlib inline
gam0 = 72.8
temp = 293.15
def gam(x_2):
return gam0 - 0.0187 * temp * math.log10(1+628.14*55.556*x_2)
x = range(0, 10000)
x_2= x
plt.plot('gam(x_2), x_2')
plt.xlabel('Log_10x_2')
plt.ylabel('gamma (erg cm^2)')
A few fixes needed; defining your function, there's an indent missing, also multiplying the whole array with ' * ' isn't working, so you can save up the values in a separate array through a for loop:
EDIT: Oh, and also while plotting, you don't put the variable names as strings, you just call them as they are.
import matplotlib.pyplot as plt
import numpy as np
import math
import pylab
%matplotlib inline
gam0 = 72.8
temp = 293.15
x = range(0, 10000)
x_2= x
def gam(x_2):
returns = []
for x_i in x_2:
returns.append(gam0 - 0.0187 * temp * math.log10(1+628.14*55.556*x_i))
return returns
plt.plot(gam(x_2), x_2)
plt.xlabel('Log_10x_2')
plt.ylabel('gamma (erg cm^2)')
plt.show()
Indent your function
def gam(x_2):
return gam0 - 0.0187 * temp * math.log10(1+628.14*55.556*x_2)
Find gam(x_2) for each item(x_2) in list x
gam_x = [gam(x_2) for x_2 in x]
Finally, plot and show.
plt.plot(gam_x, x)
plt.xlabel('Log_10x_2')
plt.ylabel('gamma (erg cm^2)')
plt.show()
Related
I am trying to plot this data as a decaying exponential, all of the data has the same x values just the y values differ. y= a*[(-1)*exp(-x/t)].
I am not getting the correct chart when it goes through. csv file In the image is the type of curve I am looking for. I need to plot all of the data in csv (preferably on the same plot) in pycharm. I am relatively new to pycharm so I am starting from scratch! (excel just wouldn't behave for this data) Willing to start fresh as well if there is a simpler way of writing the code, I sparsed this together with some help from the internet.
import scipy.signal as scp
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import numpy.core.function_base
def decaying_exponential(x,a,t,c):
return a *(-1)* np.exp(-1 * (x) / t) + c
import os
for f in os.listdir("/Users/flyar/My Python Stuff/"):
print(f)
df = numpy.transpose(pd.read_csv("D:/Grad Lab/NMR/Data/T1 Data/mineral oil/F0009CH1.CSV", names= ['a','b','c','d']).to_numpy())
temp = scp.find_peaks(df[2], height = 0)
df_subset = [(df[1][n], df[2][n]) for n in temp[0]]
print(df_subset)
plt.scatter([df[2][n] for n in temp[0]], [df[1][n] for n in temp[0]])
y = np.linspace(min(df[2]), max(df[2]), 1000)
params, covs = curve_fit(decaying_exponential, [df[1][n] for n in temp[0][2::]],
[df[2][n] for n in temp[0][2::]], maxfev=10000)
print(params)
plt.plot(y, [decaying_exponential(l, 5, params[1], params[2]) for l in y])
plt.show()
I have a following function with takes 2 arguments psi,lam and returns 1 array y.
lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))
def test(psi,lam):
y=[]
for i in range(len(lam)):
sin_psi = np.sin(psi)
cos_psi = np.cos(psi)
sin_beta = lam*sin_psi
cos_beta = np.sqrt(1.0 - sin_beta**2)
ssin_pb = sin_psi*sin_beta
y.append((lam*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)
plt.plot(psi,y[i])
return y
I would like the function to return range(len(lam))=10 plots of y on the vertical axis against psi on x axis.
However, it seems to be only plotting the same curve multiple times. Not sure what I am missing?
import matplotlib.pyplot as plt
import numpy as np
lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))
def test(angle,var):
sin_psi = np.sin(psi)
cos_psi = np.cos(psi)
sin_beta = var*sin_psi
cos_beta = np.sqrt(1.0 - sin_beta**2)
ssin_pb = sin_psi*sin_beta
return ((var*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)
for i in lam:
plt.plot(psi,test(psi,i))
plt.show()
I moved the variable outside of the function, this way you may also use it for other cases. The only other thing is that you should call plt.show() after you're done drawing.
Your code has several problems the main being that the return function was inside the loop interrupting it after the first iteration. Imitating your code structure as closely as possible, we can rewrite the code as:
import numpy as np
import matplotlib.pyplot as plt
def test(psi,lam):
y=[]
for curr_lam in lam:
sin_psi = np.sin(psi)
cos_psi = np.cos(psi)
sin_beta = curr_lam*sin_psi
cos_beta = np.sqrt(1.0 - sin_beta**2)
ssin_pb = sin_psi*sin_beta
val = (curr_lam * (cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi
y.append(val)
plt.plot(psi, val)
plt.show()
return y
lam=np.arange(0, 1, 0.1)
psi=np.deg2rad(np.arange(0,361,1))
y = test(psi, lam)
print(y)
Sample output:
As Johan mentioned in the comments, you should also directly iterate over list/arrays. If you need to combine arrays, use
for x1, x2 in zip(arr1, arr2):
If you absolutely need the index value, use
for i, x in enumerate(arr):
I am trying to plot with dots hoping in the end i can get a probability density function simulation. My code is:
import random
import math
from numpy import *
from matplotlib.pyplot import *
import matplotlib.pyplot as pl
clock_offset=3000
y=0
p=0.50
for i in range (40):
x = random.random()
if x < p:
clock_offset+=1
for 'bo' in (clock_offset,y):
y+=1
pl.plot(clock_offset,y,'bo')
pl.axis([2980, 3040, 0, 40])
y=0
else:
clock_offset-=1
for 'bo' in (clock_offset,y):
y+=1
pl.plot(clock_offset,y,'bo')
pl.axis([2980, 3040, 0, 40])
y=0
The problem is i can't write a for loop that makes y+=1, when that place (clock_offset,y) has already been occupied with a dot. Any solutions?
I'm not sure what this code of yours is supposed to do. But take a look at this answer of mine that explains how to get a random number on a distribution. Bellow I gave you a rewrite of that C++ code into python.
import random
import math
import numpy as np
import matplotlib.pyplot as plt
def GausPDF(x, a=1., b=2., c=3.):
return a*math.exp( -((x-b)*(x-b)/(2*c*c) ))
def random_on_PDF(PDF, top, bottom, maxPDF):
x = (top-bottom)*np.random.random()+bottom
y = maxPDF*random.random()
while(y>PDF(x)):
x = (top-bottom)*np.random.random()+bottom
y = maxPDF*random.random()
return x,y
x, y, = list(), list()
for i in range(0, 1000):
a,b = random_on_PDF(GausPDF, 10., -5., 1.)
x.append(a)
y.append(b)
plt.scatter(x,y)
plt.show()
Using this code and THIS matplotlib example directly, you can simulate how random voting affects/builds a PDF.
Is that what you're after?
I have a function f(x,t) = cos(t)*t + x and i want to display the change of the result over the width x and time t at discretised time steps t_i and discretised width steps x_j.
Now I am a while here on SX and feel really embarrassed to only can post such little code or in other words nothing (since nothing worked I have done...):
Nevertheless if someone has the time to help, I`d appreciate it.
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as pyplot
from astropy.io.ascii.latex import AASTex
def func(xi, ti):
res = np.cos(ti)*ti + xi
return res
timeSpacing = 100
timeStart = 0
timeEnd = 1
time = np.linspace(timeStart, timeEnd, timeSpacing)
widthSpacing = 300
widthStart = 0
widthEnd = 3
width = np.linspace(widthStart, widthEnd, widthSpacing)
resultList = [None]*timeSpacing
resultListInner = [None]*widthSpacing
for i, ithTime in enumerate(time):
for j, jthWidth in enumerate(width):
aas = np.zeros_like(width)
aas.fill(ithTime)
resultListInner[j] = ithTime, jthWidth, func(jthWidth, aas)
resultList[i] = resultListInner
So how do I correctly index the list and array and plot my data using matplotlib?
My plot should look like this:
where in my case the aperature should be the width x, the sky annulus is my time t and the RMS is my func(x,t).
A couple of points:
Numpy provides a very nice function for doing differences of array elements: diff
Matplotlib uses plot_wireframe for creating a plot that you would want (also using Numpy's meshgrid)
Now, combining these into what you may want would look something like this.
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
def func(xi, ti):
res = np.cos(ti)*np.sin(xi)
return res
timeSpacing = 20
timeStart = 0
timeEnd = 1
time = np.linspace(timeStart, timeEnd, timeSpacing)
widthSpacing = 50
widthStart = 0
widthEnd = 3
width = np.linspace(widthStart, widthEnd, widthSpacing)
X,T = np.meshgrid(width,time)
F = func(X,T)
DF = np.diff(np.diff(F,axis=0),axis=1)
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot_wireframe(X[:-1,:-1],T[:-1,:-1],DF)
plt.show()
Note that diff is applied twice: once in each dimension axis= . I have also changed the toy function you provided to something that actually looks decent in this case.
For your more general use, it seems that you would want to just collect all of your F data into a 2D array, then proceed from the DF = line.
I am very new to programming, and would appreciate some assistance with my program. I'm trying to read in arrays through a for loop, do some calculations on them and plot the result on a 3D graph, but it gives me the error:
IndexError: index 753 is out of bounds for axis 0 with size 753
Here's the code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import math
from itertools import product, combinations
from numpy import *
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
ra_day = loadtxt("RA Days.txt")
ra_minute = loadtxt("RA Minutes.txt")
ra_second = loadtxt("RA Seconds.txt")
ra = ra_day + (ra_minute/60) + (ra_second/3600)
dec_day = loadtxt("DEC Days.txt")
dec_minute = loadtxt("DEC Minutes.txt")
dec_second = loadtxt("DEC Seconds.txt")
dec = dec_day + (dec_minute/60) + (dec_second/3600)
dist = loadtxt("Distance.txt")
for i in range(len(ra)):
x = math.cos(ra[i]) * (dist[i] * math.cos(dec[i]))
y = math.sin(ra[i]) * (dist[i] * math.cos(dec[i]))
z = dist * math.sin(dec[i])
ax.scatter([0],[0],[0],color="b",s=100)
ax.scatter([x],[y],[z],color="k",s=100)
plt.show()
I don't know the language but generally an index out of bounds is when the starting and ending indexes are incorrect. Starting at zero until length instead of length-1 etc. Might be worth looking at that in particular until someone posts an answer who knows the language. Hope I may have helped