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?
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()
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()
So I made my list but after that I don't know how to take out of it my x and y so I can use it later to create a graph
import random
import numpy as np
import matplotlib.pyplot as plt
tabuletson = []
for i in range(0, 10):
x = round(random.uniform(-1000,1000),2)
y = (2*x+1)
tabuletson.append([x,y])
print(tabuletson)
wielomian = np.poly1d(np.polyfit(x,y,3))
linia = np.linspace(-2000,2000,2000)
plt.scatter(x,y)
plt.plot(linia,wielomian(linia))
plt.show()
All you have to do is to add one line of code after and outside your for loop. This command will create two lists containing x and y values. You can use the same variable names x and y.
x, y = zip(*tabuletson)
I think that this is a better way to do what you want according of how plt.scatter and plt.plot work. Hope it works as you want!
import random
import numpy as np
import matplotlib.pyplot as plt
x = []; y = []
for i in range(10):
x.append(round(random.uniform(-1000,1000),2))
y.append(2*x[i]+1)
wielomian = np.poly1d(np.polyfit(x,y,3))
linia = np.linspace(-2000,2000,2000)
plt.scatter(x,y)
plt.plot(linia,wielomian(linia))
plt.show()
The np.polyfit and plt.scatter functions you are using require separate lists of X and Y coordinates.
Try:
import random
import numpy as np
import matplotlib.pyplot as plt
tabuletson_x = []
tabuletson_y = []
for i in range(0, 10):
x = round(random.uniform(-1000,1000),2)
y = (2*x+1)
tabuletson_x.append(x)
tabuletson_y.append(y)
print(tabuletson_x)
print(tabuletson_y)
wielomian = np.poly1d(np.polyfit(tabuletson_x,tabuletson_y,3))
linia = np.linspace(-2000,2000,2000)
plt.scatter(tabuletson_x,tabuletson_y)
plt.plot(linia,wielomian(linia))
plt.show()
Note: referencing x and y after the for cycle will give you the last values from the randomly generated list:
list of x vals: [-8.78, 554.81, -693.22, 955.8, 88.95, 235.55, -108.67, -804.08, 494.65, 754.58]
list of y vals: [-16.56, 1110.62, -1385.44, 1912.6, 178.9, 472.1, -216.34, -1607.16, 990.3, 1510.16]
x: 754.58
y: 1510.16
For more info:
PyPlot Scatter documentation
PolyFit documentation
Your x and y are stored in your list tabuletson. Like this: [[x0,y0], [x1,y1], ..., [x,y]]
So you can, for example, get the value of x1 and y1 with x1 = tabuletson[1][0] and y1 = tabuletson[1][1]
Is that your question ?
tabuletson = np.array(tabuletson)
X, Y = tabuletson[:,0], tabuletson[:,1]
X will have all your xs from list
And, Y will have all your ys from list
My code below is working properly but I have an issue in the final plot where my schematic is not beginning from the common origin, but instead it is starting from (0,0) but as a point not as the common origin. How to fix it?
import matplotlib.pyplot as plt
import numpy as np
from numba import jit, cuda
#jit(target="cuda")
def func2(a):
for i in range(10000000):
a[i] += 1
if __name__ == "__main__":
n = 10000000
a = np.ones(n, dtype=np.float64)
b = np.ones(n, dtype=np.float32)
r3=np.arange(1.1,10,0.1)
r1=1
r2=1.1
h=20
kconcrete=1.4
kins=5
R1cond=(1/(4*np.pi*kconcrete))*((1/r1)-(1/r2))
R2cond=(1/(4*np.pi*kins))*((r3-r2)/r2)
Rconv=1/(h*4*np.pi*r3**2)
Rtotal=R1cond+R2cond+Rconv
Rtotal=R1cond+R2cond+Rconv
plt.plot(r3-r2,R2cond,label="resistance of the insulation",color="orange")
plt.plot(r3-r2,Rconv,label="resistance of the convection",color="green")
plt.axhline(R1cond,label="resistance of the concrete",color="yellow")
plt.plot(r3-r2,Rtotal,label="total resistance",color="purple")
plt.legend()
plt.show()
You can set the X and Y limits of the plot with:
plt.xlim((0,100))
plt.ylim((0,100))
Before the plt.show()
I want to draw a function which has periodic condition.
My code is as following.
import numpy as np
import matplotlib.pyplot as plt
from numpy import *
import itertools
from itertools import *
r = np.linspace(-1, 1, 1000)
f(r) = np.exp(-pow(r,2)/5)
In this situation, the period of f(r) equals 2. I want to plot (r,f(r)) in the range -inf < r < 1.
With using itertools.repeat, how can I plot that figure?
f(r) = np.exp(-pow(r,2)/5) isn't valid python. Just try print np.exp(-pow(r, 2)/5). Or def f(r): return np.exp(-pow(r, 2)/5)
from numpy import * does nothing for below it.
from itertools import * does nothing below for below it.
Imports are in the form of:
import blah
blah.blah_function()
or
from blah import blah_function
blah_function()
or (don't do this... ever... please)
from blah import *
blah_function()
also
float('inf'), -float('inf'), and float('-inf') are all valid in python.