设置matplotlib图的坐标轴范围
我有五组数据和它们的概率,我想用泊松分布模拟这组数据,模拟20000次。我希望x轴的范围从0到1。我试过了,但在这段代码上卡住了。有没有更简单的方法来写这个代码呢?
import numpy
import matplotlib.pyplot
import pylab
import numpy as np
from pylab import *
data = []
inventory = 0
for j in range(4000):
totalOrder= 0
totalProduction = 0
for i in range (5):
# calculate order
mean = 105
order = np.random.gamma(mean, 20000)
totalOrder = totalOrder+order
# calculate production
production = numpy.random.choice([80, 100, 130, 150], p = [0.2, 0.50 ,0.20, 0.1])
totalProduction = totalProduction + production
# calcculate new inventory
inventory = inventory + production - order
if inventory < 0:
inventory = 0
# calculate fill rate for last 5 orders
fr = float(totalProduction) / float(totalOrder)
if fr > 1:
fr = 1
# append FR to dataset
data.append(fr)
grid(True)
xlabel('Fill Rate')
ylabel('Density')
title('Simulate the system for 20000 week')
matplotlib.pyplot.hist(data, normed = True)
pylab.show()
1 个回答
1
你需要使用 matplotlib 的 set_xlim
方法 来设置坐标轴的范围。可以看看他们的一些示例,比如 这个例子,这样你能更好地理解这个模块能做些什么。
在你的代码中,你需要添加:
ax = plt.gca()
ax.set_xlim(0,1)
关于一些优化,我注意到你在不同的别名下引入了同一个模块(例如,你引入了 numpy 及其别名 np,而 pylab 也引入了它)。这让我觉得你对这个语言还不太熟悉。随着你不断学习,最终你会把这些引入简化到只有几个,比如:
import numpy as np
import matplotlib.pyplot as plt
然后你会调用这些命名空间下的正确函数(例如 plt.show()
,而不是 pylab.show
- pylab 只是 numpy 和 matplotlib 的一个简单封装)。
你的代码还有一些可以优化的地方(例如,向量化循环),但考虑到你目前的水平,我觉得这样会让代码变得太复杂。而且,循环的写法更清楚地表达了你在做什么。
也许给你一个小建议:在 Python 中,当你想更新一个数字类型的变量(比如整数、浮点数等)时,你可以直接这样做:
inventory += production - order
这样可以省去再次输入 inventory
的麻烦,减少将来修改代码时出错的机会。