简体   繁体   中英

Set axis limits in matplotlib graph

I have a five period of data with their probabilities and I would like to simulate it with 20000 times with the Poisson distribution, I want the x-axis start from 0-1, I tried but I stock with that my code here: And is there any way to code it easy than what I did

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()

You'll want to use matplotlib's set_xlim method for the axes. Have a look at some of their examples, this one for example, to understand better what you can do with the module.

For your code, you'll need to add:

ax = plt.gca()
ax.set_xlim(0,1)

As for some optimizations, I see that you're adding the same module just under different aliases (eg, you have numpy and its alias np imported, which are also imported by pylab). It tells me you don't have a lot of experience with the language yet. As you continue to learn, you'll eventually reduce all those imports to just a few, eg

import numpy as np
import matplotlib.pyplot as plt

and you'll call the correct functions belonging to these namespaces (eg plt.show() , rather than pylab.show - pylab is no more than a thin veil over a package of numpy and matplotlib.

There are a few more optimizations you could make to your code (eg vectorizing the loop), but given your current level, I think this would make it too complex. Besides, the loop does make it more explicit what you're doing.

Maybe just one tip: in python, when you want to update a variable that is numeric (int, float, ...), you could just do:

inventory += production - order

It saves you from typing inventory again and thus less chances of errors in the future if you want to make changes to your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM