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

2024-10-01 04:59:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手。我试图运行以下代码来模拟一个展台的销售情况。该代码使用calculateTips、calculateProfit函数根据销售机会预测销售的小费和利润。summalsetata函数主要用于绘制其输入数据的直方图。代码中使用了大约5次summalsetata,所以我们应该有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中运行代码时,第一个图出现了。但是,为了看到下一个绘图,我必须关闭当前绘图(显示在屏幕上)。在

问题是:当我运行代码时,我希望绘图以不同的图形显示(我希望看到它们全部在一起)。不是说关上其中一个看下一个。在

提前谢谢。在


Tags: 代码nameimport绘图ifaspltout
1条回答
网友
1楼 · 发布于 2024-10-01 04:59:17

好,为此,为每个绘图创建一个新图形:

plt.figure(1)

然后是所有的普通属性,ylabel,xlabel等等。 然后每个人

^{pr2}$

最后,为每个图形创建图形并绘制所需图形后,最后:

plt.show()

将显示所有数字。在

简而言之,一定要把一个新号码传给plt.图()和放置表演()在所有循环和函数之外。在

例如:

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

plt.show()

相关问题 更多 >