python - 使用函数绘制多个图?

时间:2017-02-01 11:36:32

标签: python matplotlib plot

我是python的新手。我试图运行以下代码来模拟展台的销售情况。该代码使用calculateTips,calculateProfit函数根据发生的可能性预测销售的提示和利润。 summariseData函数主要用于绘制其输入数据的直方图。 summariseData在代码中使用了大约5次,因此我们应该有5个不同的图。

import matplotlib.pyplot as plt  
import numpy as np  
import pandas as pd  
import  numpy.random as nr  

def summariseData(distribution, name = 'distribution name'):
    ser = pd.Series(distribution)
    plt.figure()
    plt.hist(ser, bins = 120)
    plt.title('Frequency distribution of ' + name)
    plt.ylabel('Frequency')
    plt.show()
    print('')
    out = ser.describe()
    ##plt.show(block = True)
    return out

def calculateProfit(num):
    profit = nr.uniform(size = num)
    out = [5 if x < 0.3 else (3.5 if x < 0.6 else 4) for x in profit]
    return out

def calculateTips(num):
    tips = nr.uniform(size = num)
    out = [0 if x < 0.5 else (0.25 if x < 0.7 
                  else (1 if x < 0.9 else 2)) for x in tips]
    return  out

def finalSimulation(num, mean = 600, std = 30):  

    arrival = nr.normal(loc = mean, size = num, scale = std)

    profit = calculateProfit(num)
    print(summariseData(profit, name = 'profit per arrival'))
    totalProfit = arrival * profit 
    print(summariseData(totalProfit, name = 'total profit per day'))

    tip = calculateTips(num)
    print(summariseData(tip, name = 'tips per arrivals'))
    totalTip = arrival * tip
    print(summariseData(totalTip, name = 'total tips per day'))

    totalGain = totalProfit + totalTip
    return summariseData(totalGain, name = 'net gain per day')

if __name__ == "__main__" : 
        finalSimulation(100000)

当我在Eclipse中运行代码时,会出现第一个图。但是,为了看到下一个情节,我必须关闭当前的情节(显示在屏幕上)。

问题在于:当我运行代码时,我想要以不同的数字显示情节(我希望一起看到它们)。不是要关闭其中一个看下一个。

提前致谢。

1 个答案:

答案 0 :(得分:0)

好的,这样做可以为每个情节创建一个新的数字:

plt.figure(1)

然后是所有正常属性,ylabel,xlabel等。 然后为每个

plt.hist(normal args)

最后,一旦你为每个人创建了数字并绘制了你想要的东西,最后:

plt.show()

将显示所有数据。

简而言之,请确保将新数字传递给plt.figure()并将plt.show()放在所有循环和函数之外。

例如:

def plot(ser, fig_num):
    plt.figure(fig_num)
    plt.hist(ser)

plt.show()
相关问题