[英]How can I change this code to output an histogram with colors depending on height rather than the default 'cool' I chose
This code generates a probability distribution psi_0_x_squared. 此代码生成概率分布psi_0_x_squared。 Then performs a markov chain simulation according to this probability.
然后根据该概率执行马尔可夫链模拟。 This probability psi_0_x_squared is actually the probability to be at position x for energy level n=0.
该概率psi_0_x_squared实际上是能量水平n = 0处在位置x处的概率。 After moving x 1000 times according to this probability I want to generate a histogram of position x.
根据此概率移动x 1000次后,我想生成位置x的直方图。 (The position frequency)
(位置频率)
''' Markov-chain Monte Carlo algorithm for a particle in a Gaussian potential,
using the Metropolis algorithm. '''
import math, matplotlib.pyplot as plt, random
def probability(x):
#wavefunction n=0 evaluated at position x
psi_0_x=math.exp(-x ** 2 / 2.0) / math.pi ** 0.25
#probability n=0 to be at position x
psi_0_x_squared= psi_0_x**2
return psi_0_x_squared
data_x=[0]
x = 0.0 #starts at position 0
delta = 0.5 #stepsize
for k in range(1000): #for this number of trials
x_new = x + random.uniform(-delta, delta) #I displace it a distance delta
if random.uniform(0.0, 1.0) < probability(x_new)/probability(x):
x = x_new
data_x.append(x)
#histogram
cm = plt.cm.get_cmap('cool')
n, bins, patches= plt.hist(data_x, bins=100, normed=True, color='k')
bin_centers = 0.5 * (bins[:-1] + bins[1:])
col = bin_centers - min(bin_centers)
col /= max(col)
for c, p in zip(col, patches):
plt.setp(p, 'facecolor', cm(c))
plt.show()
The variable n
contains the height of your bars. 变量
n
包含钢筋的高度。 Therefore this should do the trick: 因此,这应该可以解决问题:
for height, p in zip(n, patches):
plt.setp(p, 'facecolor', cm(height))
like so: 像这样:
a = np.random.normal(size=(1000,))
cm = plt.cm.get_cmap('cool')
n, bins, patches= plt.hist(a, bins=100, normed=True, color='k')
for c, p in zip(n, patches):
plt.setp(p, 'facecolor', cm(c))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.